Building Great Web Backends with Django ( Python ) | Sid Azad | Skillshare

Building Great Web Backends with Django ( Python )

Sid Azad, Founder at VisionHatch Technologies

Play Speed
  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x
13 Lessons (2h 49m)
    • 1. Course Introduction and Roadmap

      1:31
    • 2. Django Basics

      12:22
    • 3. Building a Hello Notes App - Part 1

      13:06
    • 4. Building a Hello Notes App - Part 2

      14:56
    • 5. Templates and Forms

      15:29
    • 6. Building a Login Form for the Notes App

      18:59
    • 7. Using the Django ORM and creating Models

      15:41
    • 8. Django User Authentication

      11:42
    • 9. Generating forms and saving data via ModelForms

      14:29
    • 10. Introduction to ModelFormSets

      4:54
    • 11. Updating and Deleting objects via ModelFormSets

      12:55
    • 12. REST APIs in Django via TastyPie

      13:39
    • 13. Django in Production, caching, scaling and other topics

      19:30

About This Class

What does a killer website, an amazing smartphone app and a futurustic plugin for Google Glass have in common? 

                                                   A Back End

Without a back-end all you are left with is an empty skeleton of a UI. Among other things, a back-end let's you:

  • Store data on a database
  • Run CPU intensive tasks (such as face recognition)
  • Provide a consistent API to read and write data

Django is a Python-based web framework that provides a vast amount of plumbing to build a web-backend so that you don't have to do it. This will allow you to focus on building more and better features into your application without worrying about infrastructure and plumbing.

Why this class?

This is a project based class and will take a practical approach towards learning Django. By the end of the class you will be comfortable with the following:

  • Setting up and Installing Django
  • Interfacing with Databases using Django Models
  • Writing basic Django templates
  • Writing Django Forms
  • Combining the above into a django app

The final project will be writing a Personal Notes app. This app will expose you to many basic patterns which will be applicable to a wide variety of Django Apps.

Although this is a beginner class I plan to introduce a few advanced  Django concepts in theory so as to give you an idea of the power of the Django framework.

This will also prepare you for job interviews that may ask you Django related questions. 

Why Django?

  • Python - Need I say more? If you love Python, you will love Django
  • Community - Django is supported by an excellent and supportive community. There are numerous Meetups as well as a Django Conference held every year
  • Philosophy - Django is build around the design principles of Loose coupling, DRY, Less Code, Quick Development and Explicit is better than implicit. To learn more about this check out Django Design Philosophies

Who should take this class

Anyone who wants to get started with web development and Django as well as get a peek into the more advanced features can take this class. Here are a few categories I can think of:

  • You love Python and want to develop web apps while using as much Python as you can

  • You are trying to learn Django on your own but prefer to speed up the learning process

  • You don't know much about web development but would like to start it right with Django

  • You have been practicing web development but would like to learn to use a cool framework like Django to develop more rapidly

  • You want to learn a new skill to market yourself better to compete for a job you would love to have

Whether you fit into one of the above categories or not, I encourage you to enroll for this class. Don't let a lack of experience with Python or web-frameworks discourage you. The class does not require a lot of experience with Python or web frameworks - a desire to learn will go a much longer way!

Transcripts

1. Course Introduction and Roadmap: - Hi. - Welcome to building Great beckons with jangle. - My name is citizen out, - and I'll be instructive for this course. - I just want to take this, - like to talk a bit about what you can expect ahead in this course. - The first lecture will deal mostly with discussing some common Web based terminology, - so you and I can start speaking the same language. - Also, - I will be giving a small introduction to jangle like a 10,000 level view so you can learn - about power jangle and what the stool can do for you. - From that point on, - our elections will take the form of screen cast off recording, - and you can call along with me. - Or you can look at the court and get have repository was Are we making it available there? - Our main product for the scores is a Notes app. - The reason I chose the notes up is because it covers a variety of simple patterns which are - applicable across a variety of applications that you can build using Django, - for example, - logging in logging out, - saving a resource to a database which in our case, - is a note retrieving from database browsing. - A list of sex resource is deleting them and editing them. - As you can envision. - These are some of the common patterns which are obligated a lot of applications, - especially in rest based applications, - any rest based application that will probably be consumed by multiple devices such as - mobile devices and laptops. - So I'm very excited to be teaching this course and again I welcome you, - and I'm looking forward to building really powerful notes up together in jangle learning - That's great, - too. 2. Django Basics: - in this section, - we will talk about a few core aspects of jangle and also start building our first Notre, - for which you will need by Tone and Jacqueline stolen your machines. - So if you haven't already, - I suggest you install them first and then listen further to this lecture. - Like many of the primaries, - Jiang Yu is also designed around a bunch of philosophies that the creators of Junk Django - chosen to drive it towards. - Some of them are basically saw philosophies that may apply to any kinds of software. - For example, - loose coupling being able to write less co two Express more. - Being able to develop quickly the drive Principle Express. - It is better than implicit, - which is one of my personal favorites, - which really means that Jangle avoids doing a lot of things under the hood that would look - like magic but believes explicitly stating something that it's doing and consistency off - behavior as well as being able to write, - suffer in a consistent manner. - The creators of Jangle have made it very easy for developers to follow the do not repeat - yourself principle by providing shortcuts and small snippets of court, - which you can use over and over in many different scenarios, - rather than having to write a lot of court again. - Products and Apsara, - Very central, - An important concept of jangle. - When you create a first app in jangle, - you're actually creating a project which is an umbrella which will be holding a bunch of - abs. - So the way to think about an APP is a unit of functionality, - an independent unit of functionality which can be probable into radius projects. - Various websites on various scenarios. - It's a standalone, - reusable, - independent unit of functionality. - To take an example, - we are building notes up. - But if we were building more than the notes app, - if you're building a notes app to doapp on after managing projects and, - let's say an old Olsen app for managing household grocery lists. - If your wife wants you to get grocery or something now a note list to do list. - It's our something that could be applicable in a household closely scenario as well as a - project management app scenario. - So jangle allows you to create an app in a reusable way so you can make a notes up. - Use it in a project which is for project management and then carry it over when you're - building your groceries up as well. - And ah, - project is just an umbrella which holds a bunch of traps. - So that's absent projects. - Now, - how do you create an app jangle? - You use the command called Django admin that has been provided for jangle, - and we will find this command to be a very useful one. - So you say django admin dot b y start project in the name of your project and this will - create a project for you, - but it also create an underlying app for you within the project. - This is your default. - This is the app that jangle will make first contact with When you are a lesbian head toe, - contact the Web server. - So we're going to see a demo of this very soon. - And how do you run a jangle? - There are two distinct ways off running a general One is the development more and one is - the production more in the production mode, - you can run jangle with various Web servers. - The most popular way of running Django is within a party of observer with a whiskey - integration into it. - Whiskey also, - Wells pronounces risky, - but it's known as ws g. - I. - Is the Web server Gateway Inter Freeze, - and it's a protocol which helps integrate certain kinds of software into a Web server. - And that's one jangle uses to be able to talk to a Web server. - So Django is integrated into a party Web server using on a body module called March - Underscore. - Wst I We will not worry too much about this for our purposes was we will be using an - embedded server, - which is provided with 10 jangled. - And this is called the Development Server of Jangle. - And that's what we will be using for building the notes up good. - It's not too hard to just take the APP Development Development Server and poured it as it - is to and to a correction server. - Of course, - you would have toe do certain configurations and install more underscored ws g I or - basically to integrate dangling your party. - This is a topic I will cover by the end of the course in the last couple of lectures and go - over what kinds of issues you can face in having a production server, - which you will not face with a development server, - because in a production server, - you will be actually having clients, - and you have to think about scaling. - What if hundreds of thousands of clients hit your genius ever? - How do you scale? - So the next topic is jangle request processing, - and I'm going to look at how jangle processes and a steep requests in a very basic So on - the high level, - as you can see the diagram on the screen the requested to see by jangle and the entry point - is the Euros not filed? - Well, - actually, - that is not the entry point that, - but to us it looks like that is the entry point when we're writing software for jangle. - So there's a fight on file call. - You are on stop ey that contains map ings off certain Urals toe. - Certain fight on functions called view functions. - When Jangle receives a request, - it looks up in this euros file for the APP and tries to match that you are that has bean - used in the browser or the mobile device by the user and tries to find the corresponding - view and calls the view which the request that has been received from the mobile device or - browser from the blind and Once the view receives request, - it's up to you as to what? - God, - You right in the view. - And you can process this request. - Do something with it. - You might save something to database, - or you might retreat something from the database. - You might do a bunch of operations on it, - for example, - for a face recognition that you might be running a face recognition software on the user - input that you received a picture or image and your face recognition software might be - calling a lot of other modules. - But the view is the entry point for request. - So you process a request and then you create an http response and you send it back. - So this is a simplistic way of looking at how jangle processes requests. - But let's look at a diagram that has bean put on the jangle project website and that will - give us ah view into a much deeper way of looking into how jangle process processing - requests. - So I'm going to go this diagram, - which is also President Jangle Project website and I was linked to that in my presentation - . - So you see these various levels off middle where the common middleware session middleware - middleware are valuable software that can be plugged into jangle, - and you can write your own middleware as well. - And what this often does is it intercepts on incoming requests and then passes it to the - view function. - And then an interception. - Outgoing responds and then sends it back to the browser. - So when request comes into Django, - it goes through various levels of middleware. - Now, - some of these winter, - where are already provided for you by jangle. - For example, - session middleware. - The CSR Middle View Middleware, - which is the cross site request forgery Middleware, - which helps prevent against cross eyed request forgeries. - The authentication middleware, - which is using used for Loggins and log outs. - So there's various middle were provided, - and you can look at these middleware in a file called Setting Soppy Wife, - which we will very shortly look at. - So initially, - when jangle issues an http request, - it will go through the pre defined middleware from the settings file and then, - if you have written your own metal where the request will also be intercepted by those - metal where these middleware probably do some kind off intelligent processing on the - request, - they might also modify the request in some way they might create a session and in sudden - request and also an obsession database and eventually your requested hit your view function - . - The view is the function that the user, - that is you will be writing for application. - The view will contain all the business logic for the application, - and you would process your request there and then you will send back a response. - Now, - once the response leaves the view, - it's going to again in the reverse order. - Hit the middle where that have bean configured in jangle. - So, - for example, - in this example, - with the http request comes in, - it hits the common will wear first, - then the session middleware, - then CSR if the new authentication and message middleware and then it comes to the view - function while when responses going back, - it's going to go from the view function to the message Middle, - where the authentication middleware CSR session and then the common middleware. - So it's in the reverse order when interest responses being sent back. - We also have things called view decorators in tangle. - An example of a decorator is in eyes locking and underscore required, - which is a simple decorator. - But a very useful one, - and it's a very common batter that you don't want the users to be able to view a page - without logging in. - So your website might be divided into pages that are okay to be looked at by the user - without logging in, - for example, - your landing page. - While there are pages, - for example, - the users dashboard that they should not be able to get in before logging in. - And it doesn't make sense to have a user dashboard with how the use of having not so if you - place the log and required decorator on top off your fight on view function that will - ensure that no user can get into that view without having logged in. - So it's ah, - it's some functionality that has bean pre defined by bite on, - sort by jangle and provided to you, - and that is in line with the Do not repeat your some principle that we talked about a - little before. - There's another concept called templates. - In general, - templates are similar to a spear Jsp pages if you have dealt with them before. - If you haven't, - templates are really generating. - HTM Oh, - from the silver sight. - So you write in HTM and file and you have some HTM according it. - But you can also have a fight on court embedded into a template which will be process on - the server side, - and it may dynamically generate more East human for you, - you could have constructs like four loops. - If else and l statement in your templates, - why don't we start building our first app? - Here is the exciting part, - right? - So what I'm gonna do is I'm gonna open a shell on a little system. - You can do this by doing control all tea and on a oh windows system. - You can just open a command window. - Or you can just open your editor if you don't want open your shell. - So what I'm gonna do is I'm gonna create a project first. - So in this directory jangle class, - I'm gonna run the command jangle admin Scott product at a project name. - I'm going to call my project ab sweet AP P S U i t. - So let's run this command and see what happens. - You see, - there's a directly ab sweet that's present now, - which was not there before, - So let me see the into absolute and see what we have here. - I see a file called Managed A P Y and A during pickled absolute So jangle Airman created - Project for Me called ab Sweet, - and inside the project it created an app also called Absolute. - So let's go into the absolute AP and see what that looks like at this point on two levels - down in tow. - Absolute slash. - Absolutely. - When I do an Ellis, - there are a few fives are generated over here. - We're going to go through these files one by one. - There's a settings up your I file, - which is a very important file because it contains your settings for the whole jangle - project. - This is where you will become figuring your databases. - There's a euros up your file, - which we talked about, - which would contain the map ings from euros to abuse. - And finally, - there's this file called Visited by which defines how jangle integrates with the embedded - Web server or any other Web server, - such as a body 3. Building a Hello Notes App - Part 1: Hi. Our goal for today's lecture is to build a small app, which is the beginning of the notes up. We're gonna call this Hello Notes. The goal of this app is to simply return a string called Hello Notes from Django to back to the browser of the user. Although we can simply return the sling from a general view as a £5 string, we will be using the jangle template ing system to return the strength. Now, before we get according, I do want to cover some more basics for little to what a jangle app is and also the anatomy off our notes up to just have a view in mind off what we eventually want to get to. So we want to build an app which when the user goes to first or navigates toe, the user is going to see a screen which will have an option to log in. The user can only log in if the user is already signed up on the system. So if I enter a user name and password on the screen and I had drugging, if I'm not already sign up, the system is going to register me. Once a user is logged into the system, they will be able to see a user dashboard. This dashboard will give you an option to add a note that we also show all your existing knows so you can browse for your notes. You can click on them and look at them. You can edit your notes and save them back as well as you can lead your notes and finally really building arrest interface to the notes up. We'll be using a Sophocles testified to build the rest. API, I testify, is one of the popular Softwares for by time to build a rest. Avia, actually for jangle and we re covering that in this course as well, which means you'll have to install testify at some point. But no need to worry about that right now. Let's just go over briefly about what tangled templates are. Jangle templates are files with an HTML extension, but these are not purest human files affords. The include HTML and decorating JavaScript. They look look just like a steamer files, except that they could have embedded markup and Ben and mark up. Is that off the jangle dumping system, which is a language provided by jangle to make it easy to write court that would execute on the server side and generate more HTML. If you write an HTML file, which is a jangle template, all the contents of this file are generated on the server side. The static HTML Every right in this file does not need to be generated because it's already HTML. But if you use constructs like four loops, or if statements in this file, they will be evaluated on the server side before eating the browser, and they will result in generating more STM dynamically, based on some data that may be provided to these templates from your jangle views, this is very important to remember, even from the point of view of Corning. When you're writing called in templates, you should remember that this is being evaluated on the server. It is not reaching the client side, even though these look like HTML files. And finally, jangle templates are extensible, which means that you're not limited to the jangle template ing language features like for loops and if statements or any functions provided within the general completing system, you can extend by writing your own bite on modules and plugging them into into the jangle tempering system, which makes it a really powerful system to use. Moving on, Let's look at the structure of Jenga. What I want to try to do here is describe what an ideal during restructure would look like for a jangle. So let's look at the top level directory, which is a project directly. Now, this is the directly for the jangle project. Inside this, we'll have multiple labs. So that is you one off over abs is the Abdi Abdi IR directory. So inside Abdi ir would lie all the files belonging to this application. Now remember that we want to make an app, a standalone, reusable component which can be plugged it into separate jangle projects if need be. So for that reason, we're going toe package everything that belongs to a nap in this directory. The first file here is the underscore Underscore in it, Understood underscored a p Y, which is a fight on file which indicates to fight on that this is a module. This is an empty file, but it needs to be there. The second file is a euros file. Not this file is an apse europhile, which means it would only contain the euros which are replicated this particular application. Then it's of used up your file, which will contain the bulk off your business logic. The euro stop you. I fired link toe function inside the view. Stop your file. Then there is a direct ical templates, which will contain all the templates that belonged to this application. The next directory Ecstatic by convention weaken. I'm naming this directory static, but you could name it something else. So although I highly recommend you name it static because that's the convention, a lot of Django programmers follow, and your code will be easy to read for them as well. The static directly contains all the static files required for your application. For example, your CSS files or JavaScript files any of your images, maybe documents or excel spreadsheets or whatever else you may want to link to from your app, which would not be modified and just be sent back from a jangle back to the browser So my static files directly has more directories inside of it. One of the directors of Js for JavaScript you could name the strictly JavaScript as well. It doesn't matter what you call it. Js of Jalisco would be intuitive names for it. Then there's the images directly for images, and they're not to see us. Us. Very powerful features of Django is the object relation member that provides you an object relation, mapper or all. Our M is a tool that allows you to map by phone classes to relational database tables. What this means is that you can write bike on classes that map to a database table, and this makes it very easy for you to retrieve or save data when you first data from a database table through an or in tow. But it has already populated into instances off the class that is mapping to the database table. We will learn a lot more about this in the next few lectures, but for now, the reason I'm mentioning this is the file models that B Y is by convention. The file inside you AB that'll contain your bike on classes that we mapping to your database tables. So now we can start calling the notes. So I have here open in the text mate editor and you can use any editor. It's better if your editor supports by time, because you will be able to see the inundation and maybe some nice colors for bite on variables. I also use Eclipse of my limits machine or my Windows machine. But texted works good enough for me on Mac, so let's just briefly go through the settings floppy by file in the absolute slash absolute directory. So just to ensure that your right file open my current pot is absolute slash AP suite, which means I'm in the ab sweet application directly, not the project directly, and I have the settings up People file open over here. So as you can see, this is a fight on file. We just lists a number of fight on variables, and these settings would apply to your whole project, which means that these settings will be applicable toe every app that you put under this umbrella project. Absolute. I would briefly go through some of the variables that are specified in this file, but not through all of them, since we'll be frequently coming back to this vile and going through different variables as we need them. So online Number three. I see debug equals true, which simply means that Django is running in debug mode and it repent out some other statements. And also it will not be sending emails in case of exceptions to whoever has been specified as an admin. You can specify the admin is in the admin stubble. Online Number six Online number 12 is the Data Basis Dictionary, which contains a list of databases. The first databases Mr is listed over here is default. The Cuban default maps to another dictionary, and this dictionary has a number of key words like engine name, user name, passport, host and port. The injured is the back and that we will be using as our database. In our case, it will be sequel like three. The name in case of Sequelae Tree is the file. The sequel lightly maps to, in the case off another relation database, like my sequel or Oracle it real name of the database itself. In case of a little bits, like my sequel Oracle or DB two, you would have the user password and host specified, but you don't need those for secretly three as sequelae. Tree is a simple database that will simply worked through a flat file listed over here in the name Klaus. You can specify the time zone for Fight On for Django Online 32. By the fall, it's America slash Chicago. But there's a Wikipedia link, which can give you a number of times on so you can customize it based on where you're located. Over your site will be located. The use I wanted and direct variable is settled through, which means internationalization is enable for John Jangle right now. But you consented to falls. If you are sure that your side will not be running internationally and does not need that support, since that will make some optimization that may make your slight site run slightly faster. Here's a directive. Middleware classes. This is a couple off different middleware modules that are plugged into jangle, and you can definitely write another middleware module and you can inserted at any location , which you deem fit for your little. The route Ural Khan is ah is a very important variable. It specifies the file that would be the first, your old file that Jang will hit when it receives a request. In this case, it is absolute. Don't euros the reason that this is requires. Let's assume that we have to applications absolute and notes. And both of these applications have their own your own files that how does dangle decide with euros filed up to invoke Jack? You can decide that based on this director, in this case, Jiang will look up absolute Don't euros file and in the euros file for a single for one application, you could easily include your own files for other applications. So in our case, from absolute or euros, we'll be including nonstop murals to redirect tango toe notes that euro. So it's a good idea to give some thought toe how you're going to design your your olds because that gives an intuitive feel to your website and makes it much more easy for a user to browse the Web site. So let's think off how the euros for our project and our notes up should be designed. So since I would be running the jangle developments, there were. My Euro is going to start a city vehicle on slash slash local host. Now the Jackal Development server can be run on any port, So let me just, uh, pick the port 8000. You can you can pick another port if you want to. So a city people and slash last locals Colon 8000. No, I have to figure out what my urine for the notes index PHP. So since I'm using a specific application called notes my Ural, it would be helpful of my Euro countries notes. So maybe it should be local host Colin 800 slash node slash index, cause that's intuitive to me. It's telling me that I'm navigating to the notes up or to something called notes, and I'm looking for the index page in it. Which means that let's say, if we have another application called to do the index space for my to do lap should be local host. Coordinate thousands slash two slash index. I hope this seems intuitive to you. So let me get this. You're a local host for 20,000 slash north slash index and I get an error page, and the reason for that is that I'm not running the Web server right now, and even if I were running the Web server, I would not find this Europe because this you are mapping does not exist. So in the next part of the video In a continuation off doing the Hello notes app, we will see how to make this. You are return the response that we expect, which is hello notes. 4. Building a Hello Notes App - Part 2: - the last time we had decided that we'll use the Ural local host Colony 1000 slash node - slash index to get to the hell of notes page. - So let's see what happens when you get this Europe Well grown gives me an error that it - cannot connect to local Jose 1000 and the reason for that is that we're not yet used are - using or running our A jangle embedded reps over. - So let's start that it's open a shell window and go into the project directory, - not the AB directory. - So currently I'm not logged into my absolute directory. - If I do, - Ellison is directly. - I see the script managed a B Y. - This is a state that jangle uses for a lot of useful companions. - Volume, - which is Run server, - which is used to run the embedded jangle development server. - So that's battle started. - I need to run by Home Man is don't be wife fronts over and the fourth number, - which is 8000 presenters. - This is what you should see. - It does you the jangle version. - It's running, - and it does. - Your settings find that it is using absolutely not settings, - so let's go back to chrome and see what happens now. - This is what it gives me a before Paige, - it wrote. - And this is what you should be seeing is that at this point, - if you don't see that, - there's something wrong with them. - But it's over. - It's not configured properly or it's not running. - You wouldn't want to check your show and see if there are any editors over there. - So this is great. - But this is not a very interesting page. - What do you want to see is hello notes, - But the reason we're getting a default page, - it's because by default Tchenguiz configured to send this page. - If there are no other Euros Peter Configure, - we need to configure the euro note, - slash index and diet to a view, - and this view is going to send us the Hello notes page. - So let's see how we can do that. - No, - since all the euros for the notes application are going to start with notes, - he should become figured one level below. - To do that, - let's go into our default application, - which is absolute. - If you remember, - this was the one thing was greeted by the Start Project Command. - This one has a file called Euro Stop ey so goingto ab sweet slash absolute slash euro stop - , - ey, - open it in some text editor of your choice. - So this is what if I looked like it has this object called Neural Batters, - which is an instance of the patterns class The patterns last constructor taste the first - argument, - which is flanked by default. - And I would say Don't worry about it right now. - It is just a convenience argument for passing a prefix. - Do not write redundant packets names in euros, - but we can revisit that. - So let's configure the first euro here. - To do that, - I'm going to add an entry here, - which is an instance of your class you are the first argument of this entry is a regular - expression, - so my euros are starting with notes, - so that's what I need to put here. - So what this expression say's is any you, - Earl that starts with notes slash. - The second argument is an include director so inside of include, - I'm going toe put the name of the file that I want to include, - which will contain the euro's falling note slash In this case, - these are all that you are always gonna figure for my notes. - So I'll say, - include notes of euros. - No start. - Yours doesn't yet exist, - but we're going to be writing its own. - So looking back at this line, - what we're saying is that any Ural that starts with notes slash should be redirected to - this other fire. - No, - start Buehrle's let's write notes slash yours of people I know. - So I just created a new file inside the notes. - I'm gonna call it your own stuff just for convenience. - I wouldn't be the same euro stop you file from absolute and based it. - Now, - of course, - what we need here is not not slash, - but what follows north slash We just index. - So what I'm saying is that you are the stock index. - There should be a certain action done on it. - But now we don't want to include anything. - What do you want to do is we want to specify a fight on view to which this you are. - You will be redirected. - So think about what's happening here. - When you had local horse colon, - about 8000 slash node slash index, - Django pulls in the absolutes like you are also FBI file it looks at the park notes of the - euro. - It looks up that it needs toe redirect that you are on that request toe, - not slash Yala's sake. - Why, - since there is an include associative, - but notes slash now, - since it's already processed apart notes of the euro, - it comes to index. - And since it us included this file, - uh, - no slash urals up. - You're right. - It looks at what should be what should happen with the with any euro starting with index. - So it looks at index and do whatever specified here, - which is index. - So I passed three arguments over here. - The 1st 1 is the Euro battery. - The 2nd 1 is the name of my view function which does not exist yet And the 3rd 1 is a name - which is an alias I have given to this Ural entry. - So let's see what happens now when we hit our euro. - The sultan named notes is not defined. - And the editor is coming from this file ab sweet slash ab sweets like you are also p y line - number 17. - So this is a nice debug output that you're looking at and the reason you're able to see - this is because Jang was running in development mode in and it has debug equals on in your - settings files. - Actually, - even even if you're not running in the development more, - if you're running with a party and whisky, - you will still see this output as long as you're debug is set to own, - So this is quite useful. - We're going to go to this, - file a file on this line and investigate what's going on here. - So in my absolute slash, - Charles not be filed. - Oh, - so it says Notes, - is not defined because it doesn't know what notes is here. - That's because no start Europe's needs to be in single ports, - so it takes in the name of the file to be included as a fight on string. - Let's see what happens now if you tell your not is a different letter, - it says the name indexes notifying. - So that's because the symbol index is not defined, - which needs to be a view function. - So let's go to abuse dot by inside of notes and define our first view of you as I mentioned - before is simply a part on function. - So d of death is what do you use to define icon functions? - So he's in Death Index. - The first argument to index is a request and what we are simply going to do from here. - Is it done an HDTV response? - Object and let's call it let's say responses. - Hello, - notes. - Now, - before I do this or run this, - I need to include the http response module over here because or the class? - Because jangle doesn't know yet what this is underlie included or important. - So what I'm gonna say is from jangled on a CTV packet import HDTV response, - they should be good enough. - So let's see what happens if we hit it again. - I get name indexes notifying. - That's because, - you know, - slash euro stopping by does not know where the where the symbol index is coming from. - So what we can do is we can say from notes, - start views, - import index. - They should fix it refreshing. - There you go. - Hello, - Notes. - So this is your first output from your view, - but we wanted to send his head of notes output from a jangle template and not just your - bike on strength. - So let's see how we can do that point back to used up you. - Why we don't have any templates that exists right now. - We're going to create one in the Notes directory in the North application, - create a new directly call temperance inside the North slash templates directly. - Let's create a new file and call it index stories Demo and let's open this file. - Next meeting is by default. - Put some output in my Stephen file, - but that's not what I need. - So all we even this html file is Hello, - notes on Just to make a local little bigger will use a header history and we will call it - no notes now, - although Everton attempted, - I'm not really returning the template from my view function. - So that's what I need to do. - Nice. - So instead of sending this http responds with Hello notes, - let's send it back. - We are templates to do that. - I'm going to be based in these three lines and let me go over them one by one. - The 1st 1 is template equals loader. - Don't get template indexed, - Oresteia Law Order is the model in by count that lords templates. - So we're saying load the industry steam attempted inside the variable tempered the second - line is R C equals request context. - It takes The first argument is a request, - and the second argument is a dictionary to which I'm passing the current user. - So I possible Kiki User and I passed requested user to it, - so gentle by default, - has the current user inside the request. - In our case, - there is no current user because we haven't created the dark logic for the user Logan's. - So it will probably be an anonymous user or none. - So the last liners were during a CTB responds, - and it takes us argument template or render RC. - Now, - if you remember, - STP responses what we were turning when we were turning the Hello Notes response, - which was just a pipe downstream. - The definite don't render method will rendered attempted using the request context RC, - which means it will use the request as well as a stationary that we have Boston to create - the tablet. - The one more thing that you need to do is we need to lord certain symbols, - because right now our view does not know what a loader is. - So from the jangle don't tempted package the important order and request context. - Let's see what happens when we load the space. - Now I get attempted does not exist. - What this matter means is that Jangles does not know where our investor external template - is. - It's in the north slash templates directory, - but Django is not aware of this directory. - As you might remember, - having a directory named Templates inside of an application is a convention. - You can also named historically something else, - but it's a good idea to name it temperance, - so the baby can tell jangle about this directly is by going in absolute slash settings. - Don't be I filed and looking at the stubble template underscored EI Ours, - I'm going to add in single ports. - Note slash templates. - By doing this, - I'm telling Django that one of the directories in which templates can be found its north - slash templates. - So now that we have done this, - let's see what happens. - I refresh the page and wallop. - Here's hello notes, - and it looks bigger and darker because it's in the East pretax, - and this is a confirmation that your output is actually coming from the temple. - There's one final thing I would like to show you in this lecture. - You remember how we had a very medical user assigned to request a user. - But this isn't gonna do much for us because we don't have databases configured and jangles - . - Authentication needs databases, - too. - Be able to have ah users and request a user. - So what we're gonna do is instead of user, - we're gonna change this variable name to use her name. - And instead of using requested users the value for the key user name, - we're going to use static value such as my name citizen. - So we're passing the variable user name and the value of this variable its citizens to the - template. - Let's see how we can use this in the dump it. - So I got a note slash tempted slash industries Deimel and instead of north in double curly - braces, - I'm going to write user name. - Let's see what happens. - Refresh The page says hello, - Sitters up. - So this is an example of how you can use in these double curly braces any variable that you - have passed into you're tempted. - We are the reports context. - From your view, - this concludes this lecture and our hello notes are We will continue this application in - the next lecture and we'll be learning more about jangle forms and using a jangle form to - create our log in page. - Until then, 5. Templates and Forms: In the last lecture we created a hella notes up using general templates. In this lecture, we will learn a bit more about templates, the more advanced or interesting features of templates that jangle provides. And we will also learn about jangle forms which are powerful way off, creating HTML firms. We abide home code, and finally, we will wrap up the lecture by creating our own Logan from for the log in page. The average the user will be able to log in. So Jang with benefits provide you some very powerful features, one of which that I find myself using very frequently. It's tempered inclusion, which means that you can write a template and you can include the template in other templates, which means you can write a genetic template. For example, if there's a rigid or a piece of HTML code terrorist occuring frequently in multiple pages of your website, you can write a signal template and have the peace. Of course, in that dump it and then you can use the goalie bracket open person dial include and template name, director toe include the tempered inside other jangle templates, so you don't have to write that is chemical again and again all your pages. The second similar feature is stunned of inheritance, which is similar to inheritance in an object oriented language. If you talk about it, what that means is that you can write a template, for example, of base HTML template, and you can have all the templates off your website derive from the bassist email templates . Now, why would somebody need a feature like that? Take an example off a website that has a header with the menu. It has a footer with all the links to your about contact and blocked pages and then in the centre. Each page has its own content, but the header and footer are conquering on each of the pages, so there's actually two ways that you can do this. With jangle, you can use inclusion to create two templates called Header Noticed him and footed or East Yemen. And in each of your pages you can include the header and footer Temperance and have the content in the center in each of your templates. But that's a bit cumbersome because you have to remember to put the header template at the foot, attempted in each of your page. To avoid this, I can use tempered inheritance to use temple inheritance. I would write a template. Let's call it based on HTML. I would put the esteem in court for my head on top of attempted. Then in the center I would put a block, which would be a placeholder, and I can show you later how to use it in a further lecture. But below that block, I would put the court for my footer HTML. Now, every template that derives from bay stories TML can replace this center Brock between the header and a footer and place its own content over there. So all you have to do is to say on top off any other tempered extends based on HTML in curly braces percentile, and that will result in that Dr template driving from based artist Yemen and automatically carried over the header and footer. So as long as a template derives from the story CML, you automatically have header and a footer for every page, and that makes life a lot easier. Next up, the Jackal templates also let you use some programming constructs in in a very quiet sonically, for example, you can use a fore end for you so you can integrate through lists or couples or dictionaries, and you can print the fender contents or create lists out of them or what have you. You can also use FNL statements and a number off relation operators to operate on variables that have been passed. The template filters are not the bolivar mechanism. Don jangle dumpers provide you off interest a directive which you can place after a variable separated by a pipe. And by doing that, what you're doing is you're running the contents of that variable through that filter. Ah, filter would be something very simple, such that it converts of variable like a string toe. In upper case or lower case you're you have a bunch of filters available from jangle by default, but you're not just limited to them. You can also write on your own custom filters or custom tags, so the next bullet point is custom ties. In an example that I've given is variable piped camel case. What the writer off this custom tag contents do is to convert the variable or whatever the value of that variable is into camel case or capital case now. This does not come in built in Django, but you can easily write a custom tag called Camel case, which would really be a part on function. That except one variable and convert into camera case. So the idea is that filters can be very powerful mechanisms for expressing yourself concisely in templates, and you can extend the attempted language itself by writing custom ties. We would see an example of this later, So after studying all these things about templates, we will be experimenting a little bit. But all of these director, for example, four loops. And if statements and filters in our temple example index story. Html, Let's move on to farms next. So what are jangle forms? General farms are representations off HTM and forms in the form of a pipe on class. So why would somebody want to ride a bike on class for some for form? But you can easily express an HTML. The reason is that if once you write a jangle form in the form of bike on plus, you can easily use it or a lot of places on your summer Psycho. Secondly, a jackal form provides you the ability to validate a farm on the server side after validating inform. It also has a mechanism in which you can easily reload, a form of validation feels. And finally, once you're farmers posted and you get the variables back on Django on a summer side, ah, form automatically converse your variables into python classes or fight on data types, so there are many feels that you can have a jangle form. The some of the common ones are character field care, field or email, field or date time field. But a list of all of us is present on this selling that I put here from the General Project page. There is another tool called more inform in jangle, which will be more clear when we're using jangle models. But the utility off mortal form is to combine a database table moral along with the farm. A lot of times, your forms and east Yemen mimic the structure off a database table. And so instead of writing a data base model, Anna form corresponding to the model Modern form allows you to integrate the two and have a single construct moral form, which would be driving from your model so In other words, it's really an automatic form, which is we generated from your database tables. Morning. We will look at this later in the plants when we're looking at more grants topics. So now let's we want toe playing a little bit of templates and verifying all the constructs that we talked about, such as Four Loops and if statements and filters. So to do that, what I'm going to do is I'm going to use the index stories demons template and copy it into a separate attempted called example. Noticiero. The reason I'm doing this is because I want to use index Therese Thiemo for, uh, extending over notes app So I don't want to cut up. Dissed, attempted are using it for our example. So let's just create another template called example totems html inside of the note slash temples directory. For now, I'll just copy the contents of index stories tomorrow. Here, let's write a new your old in the Notre and call it examples. So no start euros. API. Why? I'm adding a New York gone example, and it's going to go to the view things out, and I'm going to name an example so Let's go to abuse up ey and ride this new bike on function, for example, it's taken a request. So what do we want to do in this function? But we want to return the template. Example. Doris Thiemo. So I wouldn't copy the court from the index view over here and just change the template name to example police GMO. So I'm gonna open a new browser window and type in the URL. Local host 8000 slash notes slash example. It says the name example is not defined in line in line 20 of your old stuff. So let's see what happened here. The reason is that we don't have the important example function. This should fix it. Then it says Tempted does not exist. That's a lot because we just Oh, that's because I have named attempted example story Stephen, while in my view stop you I I'm using example noticed Yemen. So I just fixed up Refresh the beach again and here's my output. Hello, citizens. I just saved my attempted It wasn't safe before, so let's do something more interesting. This tablet I want to demonstrate how to use a bite on four loop inside attempted. So to use a for loop, what we need is a structure which I can iterated like a by home list. So let's make a list off fruits. It's clotted fruits impact on you made a list by opening and closing square brackets and then just adding whatever values she wanted it. So just put a list of your favorite foods over here. I like bananas. Very. And let's securities. So I'm passing to attempt it unless called fruits, which has a list of these foods. What I want to do on the example Space is to show this list as a list HTML list. I should have his user name variable over here, but I'm not passing it anymore, so I'm definitely to get a complaint from Django. Let me just play, Start were able in here as well. The same would be had it before. So going back to examples at least, GMO. This is how you write affordable in jangle templates open bracket percentile for fruit and fruits and to end the formal, I just use the same directive with open bracket percentile and say end for outside this four. Look, I'm gonna put my, um for my Kemalist and then I'm gonna kill, is it? And for each element, I'm going to use an Ella. And here I'm going to the same way that I have used the user name were able here. I want to say fruit. So let's see if this works. Here you go bananas, Berries and keys. So that's how you make a for loop. In general templates. Let's try playing a little bit of, if statements. So let's say, on the basis off today's temperature, we wanna friend a string saying whether it's ah, nice day or is too hot. So going back to my editor, let me pass value off today's temperature in the very built them to the stem pick. So just a baby of passing other variables. I'm gonna pass a new one, I called them, and Mr Value of 10 which is 80 right now, will be fast and in my example stories. Temo. I've put this coat over here. Uh, it's calling Brackett percentile. If temps more than 80. It's a nice day. And then in college, back bracket person dial else. It's too hard. So if temperature is smaller than 80 I should see It's a nice day. In my case, the temperature is 80 right now, so I should really see this l statement. It's too hot, so let's see what happens. I see it's too hot. Now let's see the temperature to something better like 72 degrees and the fresh. So it's a nice day. So this is how you use ills if statements. And of course, you can have Ah, multiple L statements over here, so I could say if temperature is between 70 and 75 so it's a nice day. If it's lower than 70 say it's too cold. It's fairly easy to do that just by using and if else construct just that they use in any programming language. So the next thing we want to look at our filters, we'll use one of jangles redefined filters called lower. So you do see how in this webpage my name is in a capital case. What if I want to convert it to your case? Either I can pass it as lower case in my court by just converting the strings citizen into lower case or I have the option off just going to my attempted and filtering this variable by I think it through. Jangle, template, attack or lower. What do you fresh it? My name is going to lower case to see how simple this force and this is the power of attempted bags and you can create attempted attacks. But I didn't fight on court, so it really makes your ability to extend the Django attempted language infinite, just only limited by what you can write in Beit Home, and that's what makes it so powerful. So in the next video, we will actually create a jangle form and render it to our index story steaming page and give away for the user to Logan, because that would be of the way for us to connect our application to a database and actually take the email and passwords input from the user and either stored in the database for a new user or verify it against the database and have user logged in. And that's what we're going to do. Our next lecture 6. Building a Login Form for the Notes App: - the goal of tourist accidents to create a form that will allow the user to log in. - While doing this, - we will also be exploring some of the features for validating jangle forms and how to - propagate annettor invalidation Back to the user in the browser. - Open the views Top. - You have fired for the notes application. - Now, - in our index view, - we can create a new form called the log in form. - Now imagine if you were creating an A C. - M. - A form for a user, - Logan, - you would probably have a user name feeling a password field and a button for submission. - We're going to do the same thing in our Logan firm using a jangle form. - So the first step is to create a long inform class for which I simply have to create last - name Logan form, - which derives from forms don't form. - So this is how I create a new class for a former jangle form. - Now, - what should be the conference of this class? - I need my fields, - that user name and password fields, - so I will create a variable name using them name. - This is an instance variable, - and this is going to be an instance, - off forms or email field. - I could have made it an instance of the form So Care field, - which would have made it a character input. - But I use an email field because I'm going to be using e mails as your user name for users - because it's a very common pattern on the Internet. - The benefit of using an email field as opposed to a character field, - is that there will be some validation on emails that will be provided to me from within - jangle so I wouldn't have write the code to check that email is a valid email. - For example, - it has an after eight sign and a dot calmer dot net or some sort of dopamine associated - with it, - so that validation will be provided by jangles email feet class. - To me, - the second instance variable here is the password, - so this is a simple character fuel, - but we're going to pass something called a digit to its constructor, - so visit equals from start possible input. - What I'm doing here is I'm asking jangles character fueled to render this widgets html. - Using something called password input by default, - character, - field or chair feel would be rendered using input type equals text anus Thiemo. - But since this is a passport feel, - I wanted to have some special characters, - for example, - showing no text or not showing a text or showing the text as access or dots while typing - the passport. - So that is some sanity. - With this Richard to pass for input will automatically provide to me. - So this is how likely uniform it's as easiest this. - Now what do I do with this from Since I have it here, - what I'm going to do is I'm going to pass this to my template. - By doing this in my index view function, - I'm gonna pass a new variable called form and I'm going toe assigned this variable a new - class called logging form. - There's one more thing I need to do. - I need to import to angle farms package. - So what I want to say here from jangle import forms, - Otherwise this symbol from some form would not be found. - So once I had this, - I need to use this form somehow in my template. - So that's going to index story steam o. - I have places come to block off court which are going to uncommon enough and I'll go - through this line by line. - So I'm declaring a normal HTML form by Singh from name of name equals log in for him. - Action equals slash node slash index, - which means on submission I will be going back to my index view with all the post of data. - I'm specifying the method of the form to be a post method. - And this is something I'm specifying over here called CS out of token, - which is required for preventing cross site request forgeries. - Don't worry about this right now. - We'll come back to it later when we're going over security. - The next thing I do here is declared the forms formers a variable called as underscore. - Be so What I'm saying is farm dot as underscore p and this feels in human ate all the - fields of the farm automatically over here. - So once this is done, - your form which has user name and password feels, - will automatically appear over here on your HTML page. - You don't have to explicitly type input type equals text. - So this is just example off convenience that forms offer for you. - The next line is in poor, - typical summit, - which will simply put a summit button over here for submitting my forms. - The next side is interesting, - so a jungle form has an internal data, - sexual call letters. - And this editors is a dictionary through which I can get access to any editor that has - happened while submitting a form. - For example, - in our farm there's an email field, - and if I don't type in at the rate character in the email field, - that's an error, - and the jangle form will flag that enter and generate an error message for that. - So this dictionary form don't editors gives me access to these letters, - and I'm a trading over this dictionary. - If you have worked with bite on that, - this is the normal way for it. - Reading over any pipe on dictionary. - So four field comma errors. - Their field is the key and others are the values in the dictionary for field comma errors. - Informed of editors of items, - I put this in a percentile curly brace broke and inside of this block, - I am printing out the value off the errors in here, - which are the value off the key value dictionary and then I end the for you. - So this is how I would attach the farm to my HTML page. - Let's see what happens when we involved the euro. - There you go. - Now we have a form but user name and possible feels. - Now let's try to submit this form, - so I'm just siding. - X y Z and ABC is user name Impossible and pressing Summit. - Let's see what happens. - Nothing happened. - So what actually happened when I pressed? - Submit is the forms Action did get involved. - It involved the index view. - So let's verify that it actually got in world. - I'm going to press him it again with the same input, - ABC and X Y Z, - And I'm gonna monitor the shell window on which my embedded Web servers running. - So I press submit and you see this new request appears over here. - It says this is a post request and it's in walking the euro slash node slash index. - So that's what is happening when I'm hitting my form and I'm getting the same page back - because that's for my index view does so it actually is working correctly, - so let's make our index view take care of this form because right now it's not doing - anything with it. - So since we are in walking the same view, - this view is responsible for two things now. - Initially, - it's responsible on getting a get request to return the index receive a page with an empty - form. - But once it received the farm in the form of a post request, - it is supposed to validate the form and in case often enters, - propagate these letters back to the users. - And if the farm has no enters, - this view is also responsible for signing of the user and looking in the user. - And the user's already signed up just logging in the user and then redirecting us to the - dashboard. - So this view will be doing all those things. - So piece by piece, - we're gonna make this view, - do all these things So start. - But we need to know what kind of request is this get or opposed? - And to do that, - I'm going to say if requested matter equals course. - So the request has a very recalled method which could be set together, - poster head or whatever. - Http. - Request has been received. - So now I know that I have a post request in this block inside a Ziploc, - and I can do what I want with the forum in this block. - So what I need to do is to check if all the variables in the post Request are valid. - So the way to do that is to create a new instance of the form and parliament rise it with - request our post. - So in a jangle view, - the requests variable contains requested get and requested post, - which are variables off types. - Query sets. - Cory sets are not dictionaries, - but they act like bike on dictionaries, - and they will contain all the variables that have bean sent by the user. - So our case and the user submits the user name and password forms the request are opposed, - will contain the user name and passport as keys and the values as the values of the history - . - So we have involved our form with the perimeter request off post, - and now we're going to check if the form is valid, - for which we will simply do this and for knowledge is print out. - A statement here saying form is vetted else form is not about it. - And just to make sure it's also put out a statement here saying, - received the post request. - And now let's try submitting this form. - It says Form is not Put it off. - The same received proposed. - So the reason the farm is not bad is because we have an email field here, - but we're not passing a valid email. - Let me pass a valid email like sit Azadeh demon dot com, - which is my email, - and put a possible and I'm going to something this form again. - This time, - it says, - received polls form is valid. - That's because you pass about it. - Email. - So this is us a small example off the power of farms and how it can help you reduce the - amount of Cody right? - Because otherwise you would have invalidating your farm and JavaScript or using a different - plug in. - Now, - since Django forms email, - fields have their own validation routines. - You don't have to do that. - It's not that we know how we can pick between about invalid form. - Let's think about what we need to do. - If our form is vetted, - then we will be proceeding with the user registration or Logan. - I'm just gonna put a comment here for now, - but the farm is not about it. - I want to let the user know that the former is not valid. - How do I do that? - I need to send the same page. - Index released him back to the user, - but this time I need to send it the correct instance of the form, - which contains the information that the farm is not valid. - So to do that, - I can just copy these lines. - 10. - Political loader don't get tempted and are Sequels because context and send back in a CTB - response the same way I'm doing it. - In the case of a get request off course, - is that some repetition of court? - And we We will try to re factor some of the court here. - So instead of saying form and forming a new instance of Logan firm, - I'm just going to use the same instance of Logan form that we created over here and better - moderation Request are forced and I'm returning the template. - Let's see what happens now if I put itself with something invalid and user name, - which is not an email, - it says, - enter about it email address. - I shall eat saying it twice, - saying it twice is because formed or SP by default has the other information is printing it - out So we don't really need this. - But it's still useful to know that this is how we can render enters for fields separately, - field by field if we need toe. - So let's just remove this and do this again. - This time I see a single letter, - but it tells me enter a valid email address. - So let me do that. - I submit and the form get summited and I get back to the investigators team of beach. - So what happens? - And it happened in the valid scenario is that it just said form is valid and then it grant - ahead and executed this cold for the get request. - Actually, - that is wrong, - because I should not be executing the court for the get request. - I should put it in an else block. - And what I'm going to do now is in the case of the former is valid. - I'm going to use something called redirect and give it a new name for dashboard. - So what I'm saying is redirect me to the dashboard page if the form is valid, - but we don't have a dashboard base yet, - we would have a create one. - So let's go to note, - slash your old stuff and enter a new page. - You are old. - We're going to call it cash for of You will be called dashboard as well, - and we will give it a short name off dashboards. - So this short name it's going to be used in the redirect. - And that's where this aliases useful now redirect is a function that jangle provides to use - to quickly be able to redirect to different euros from your views. - And this function is present in django dot short goods, - which is a jangle package which contains a lot of useful shortcuts from its really - important redirect for now. - So if the form is valid, - we're redirecting to the dashboard, - which means that we need the dashboard view. - So let's write it does that worldview will simply contain the same sort off court for - loading and showing a template, - except that this time the tempted will be a dashboard or East Yemen template, - which does not exist right now, - and we will be creating it. - So I changed, - attempted to dashboard, - or HTML, - and I changes dictionary to an empty victory because we're not passing any variables right - now. - And let's create the dashboard or East team of dumping, - which would just a dashboard for now. - So let's try to make this work. - I put around an email and I'm submitting. - Oh, - it says Dashboard is not defined and the other is coming from your old stuff. - You I That's because I have not important dashboard in your will stop you. - You know, - instead of saying index, - example dashboard, - I could simply say from noticed our views. - Import star Uh, - it's usually a good practice toe. - Enumerate the symbols that you're exporting or importing from ah jangle module Baikonur - module Just because it gives the reader off your code and idea where the symbols are coming - from and also it does not platter yours. - Yours name space. - Because if you are importing a lot of symbols by using star, - then everything in the module is coming on into your python interpreter structure. - And that's not very good, - because if you have a big module with a lot of symbols and you're not using all of them, - then that would make your courts lower. - But in this case, - I'm just gonna say star, - because we're probably going to be using all the views from no so views in this your file. - So let's see if it works any better. - Now submit? - No. - So it says no. - Stop used or index the non return a CDP responsible. - So what we needed to do is return the redirect, - not just say the direct. - You still have to return something from the function and redirected generator http. - Response object and turn to the browser. - So there you go. - Now we have this from tally ready, - where you can type about email and passport, - and press omits and you are redirected toe, - dashboard page. - But what is missing over here is the actual creating a user in the database. - And if the user is already registered on logging in the user and that's what our next - lecture will focus on to see how we can connect Django to a database secret like three. - How we can add use us to the database by signing them up and how we can log in signed up - users before you start the next lecture. - You should have secret, - like three in Seoul on your machine because we'll be using it and connecting to it 7. Using the Django ORM and creating Models: we're going to talk about jangle models and databases. It is important for this lecture that you have sequelae three installed on your machines if you don't suggest you do that first and then opened this lecture because we will be needing it and I'm going to be walking you through how to connect to sequelae were tangle, so data disconnections and settings in general can be specified on the project level. In the sudden stop ey file, there's a database dictionary that we had briefly looked at, and this is where you can specify your database connections. You can collect a multiple later basis, but there's a default database that you can connect to, and by that it means whenever you have not specified explicitly which database you want to execute. Aquarium Jiang will assume that you want to connect to the default database to specify the full database. You use the default keyboard as a key in the dictionary data basis, but of course you can have multiple databases. But if all you could be connecting sequel like three, but you could also be connecting toe oracle, and you could also be connecting to an object database like mongo db General establishes the connection with your database is the first time it receives a query from a user. The jangle script managed up ey, which we used to run the jangle embedded severed. Also provide your command called Sing TV Sink TV. As the name indicates, syncs all your data base models with your action databases. What that means is that let's say you create a new moral call. The user morning, which has several fields like user name, passport settings and other feels pertinent to the user. When you run Sting Devi, Django is going to go ahead and create database tables on the database so it will create a user table, and it will create all these fields in the user table. Now this is an optional step. You can always keep it and create your own table by using the sequel. Create Table Command. Singley will not create a table if it already exists, so you don't have to be afraid about single. Be over. I can you database tables and also once you dig your model, for example, if you add a new feel to the user, let's say the user certificate or user I p address. Django is going to go ahead and update the user table automatically when you're in a single command. So let's talk about jangle models. Simply speaking, a jangle model is a pipe on class that maps to a relational database or an object database table. So one morning from one table. No, let's think of a scenario where you want to get a list off all the users off your website but into your system and make a list off user objects out of it. The user class is something that you have created and you want. Accounts for the results of your secret query selects time from users into a list of these user objects. What you would do if you don't have an object relation mapper is you would do the sequel queries using maybe Jerry B zero nly BC on. You would get back results that object then you it read through this results that object, and you would create user objects for free or class instances off your class and you're assigned the appropriate field retrieved from the database to the appropriate instance. Variables off your user objects. This is a lot of work, and it's kind of tedious toe. Having a jangle model takes the burden off this logic away from you. So if you execute crazy using a jangle model, you would not get back results it. But he would get back a list of user objects, so the translation has already been done for you. Additionally, Jangle or I'm also provides you a query language. It makes it much easier to do simpler and a bit complicated sequel statements as well. I would not propose to use the jangle order for very complicated queries that have joining joints over multiple tables because it gets really tedious and murky went once you get 30. But for relatively simple and intermediate difficulty level queries, Jenga Warum can make your life a lot easier. We will be putting our jangle models in a file called Modern Stuff. In a general model, you can have various fields just the way that in the jangle form you can have various fields. There's char field in teacher field, date field and many more. And then there's a logic in jangle, or, um, that would automatically Mathies fuse to the current relation database type based on what data base you're using, for example, the chair field. If you specify a max character, land in your mortal, would Mato a back fracture field in your sequel table off that same character, Land Jacko Arms also reduced. Specify relationships between tables. For example, you can use the primary key equals true inside of your fields. To specify that a certain feeling your model is a primary key. You can specify foreign key relationships between tables, and you could have many to many relationships and 1 to 1 relationships as well. This constitutes a bit more advanced part of Jang Warren, and we will take a brief look at it at the end of the course. So at this point, we're ready to set up sequel lightly with tangle. So let's go to our shell and look at setting stuff. You are so on the top of setting stopped by. There's a database dictionary in the later his dictionary. I'm going to specify the engine as jangled or DVD Baggins off sequelae tree. Next, I'm going to give the parts to my secret lightly file in the name attributes. In my case, I'll be using a file named users slash sit. Assad slash data slash absolutely dot db This is the file of secret life we will be using toe Persist my data and that should be it for sequel Light. The attributes, such as user password host on Port I'm not used for sequelae Tree. But if you're configuring a database such as Oracle, DB two are my sequel are Sequel Server. You would be using these attributes. So now that we know that Jango can connect to a database, let's write our first morning open not slash models, not B y. So there are seven models we can create. We need a representation of the user. We also need a representation off a North class. A note object in the little bees to storm notes there. Now, we don't really need to create a user model because the jangle authentication system automatically provides a user model for you. The table doesn't exist, but it will be created when we don't sink TV. If we choose to use jangles authentication system, which we will. So since we don't need a user's model, let's create a note model instead. So to do that, I'm going to create a note class and I'm going to drive it from modern start model. Now let's think about what a torture have. Maybe, you know, should have a title, and maybe it should have some texts associated with it, and also it should have created and the owner off a note. So let's give it an owner field. Now. The order feel should be the user who has created the note. But we also already have a user table, and we don't want to replicate the feuds for use a table. So we're going to make that a foreign key and correct to the user table. Now we don't know what a user looks like. It is not specified in moral top ey. So we're going to import the use of symbols from a package called jangle dot con trick dot art dot models, which contains jangles redefined user class, which is used in jangles authentication system. The next feel should be the title off a note title equals cat field, and the car feel is going to have maximum. Let's say, off 100 characters. And then there's a text of the note, which is also charged field with the length off. Let's say 500 characters. And finally, we want the date or time of creation of the North. So let's make it create time equals date, time field. This is what our North more looks like. This table does not exist in the database yet, but we will next run the sink TV Command and try to create these tables. So I'm going to go toe to the Shelvin over my development servers running. I'm going to shut it off. And instead, in my project directory, I would drink, fight on marriage off sink TV and see what happens. So looks like Jack was creating a bunch of tables. A lot of these tables start with a uth underscore prefix. These are tables, useful authentication and permissions there, also used by the jangles by the jangle admin system, which we will learn about later. There are some internal housekeeping table, such as jangle session, which is used by jangle to maintain sessions. Now the one thing that is missing from here is our notes. Still, we don't see it anywhere here, and there's a reason for that. Simply. We will only create tables for models inside of APS that are specified in your installed APS couple inside of your setting stop you, I file. So let's add notes. Toe installed ABS open settings Don't be. Why, from absolute absolutes slash absolutely and look at the installed obstacle and add notes over here. So we're registering our application notes with the absolute project. Now, since you're already begin this process, let's just press Yes, over here. When Django asks us, you just install jangles old system, which means you don't have any super users to find. Would you like to create one? Now I will say yes, Another creative super user. It's so just me. The user name sit is up, but I won't use an email, so I'm going to say cities are a demon dot com. You can use your own email because if you use mine, you might stop sending me emails. And my even letters is the same as my user name and my possible it. I can keep anything in my passport, so I just enter PWD actually and entered it again and General Say's Super User created successfully insulting indexes. Now we verify that our table actually got created. Let me open a new shell window and I'm going to run secret like three, which can be run from the command prompt, and I'm going to give it a zone argument, my secret likely file that I had set up in my jangle instance. The user citizen data slash absolutely on TV. So here's a secret like command shell. I want to see what databases have been created. So what I can do for that Second on the command Select Star Front Secret like underscore Masters and ended with the same equal. Actually, it's secret light, understood, master, not masters. And I see a lot of output, which is all the tables that Jang was created and all the indexes that have been set upon the stable. So let's go to the interesting one. The Auth user table. This is how are users would be represented in the tangle system. So every table created by jangle Warren has an I D. Which is an indeed you're not know, and it's a primary. So our user stable has an ID password last open, whether users a super user, a user name first name, last name email is stop is active and they join. You're not limited just by these feels there is a way to extend jangles user and plug it into jangles authentication system and add your own fields to your user class. So let's see if the user table contains something. Right now, though, Cilic stars start from All user, and it does the user ID's one, and there is something in the passport field, but my password was Peter Beauty. So what jangle does automatically for you is it creates an essay encryption off your passport and stores it instead of creating a drop acid and storing it. This is because it's really bad practice toe store raw passports in your databases because if your system is hacked and people can look at Euro passports, but yesterday is, ah, one way encryption. So you don't have to worry about that if your passport is encrypted and stored in the database, so jangle automatically does that for you. This is probably my last log in time, Andi, my email and my user name and some of the data. So this verifies. And if this is working for you, it verifies that he was successfully connected. Jangle your sequelae. Fidelity's, but we're not done yet. We still have to get Cindy to create our notes table. So since we have the notes, app, install lapse, that should be relatively easy to do. Now we just need to run single again. Okay, so we got in error saying Foreign key is not defined. Not that simply because we have forgotten toe add a prefix the module prefix to foreign key in our model stop ey. So let's go on fixed up. That should do it. And we're going to see phrases issue with other fields as well, like chair feels and daytime feels, so that should be fixing as well. So that's one thing TV again. So we see a new line here, creating table notes, underscore note. So even though the name of our model is not the table the jangle creates is notes underscore note because it always prefix is the table name by the APP name over after school notes on the table inside the apus call note. This may or may not be useful to you, but the General Modern does provide you a way to provide a custom table name. So if you want to call your table my special notes on my awesome notes. You can always replace it by using the meta director in a jungle waters file. So not that we have created a note stable, and we have our user table already created by Django. We're in a good place now to start authenticating users and creating notes. In the next lecture, we will see how to authenticate users and love them in. 8. Django User Authentication: - At this point, - we have everything we need to be able to log in and look out and authenticate the user. - General provides us a lot of tools, - which allows to do the same. - Most of these tools are in the jangle dot contract or ought package. - We have already looked at something in this package, - which was the jangle contract that Auditor Model Start user class, - which represents a user in jungle. - So there are three main methods in the contract art art class. - They're actually a few, - but these are the three matters that you will be using the 1st 1 of the authenticate, - which checks by user name and password, - the presence of the user database and validates the user name and password and returns a - user on validation. - But if it cannot find the user, - or if it's a wrong user name or password, - it returns unknown unknown object. - The second method. - Logan Associates a user object to a session and finally log out disassociates that user - object from the session in jangle when your query model. - Instead of saying something like select star from user, - you would use the users or objects don't get or users or objects their own metal. - There are other variations by which you can filter, - in other words, - provide where clauses for your query. - So when you say user don't objects are all, - you're essentially doing something like select style from users. - When you're doing user, - the objects don't get and specifying an attribute on Mr Search for, - for example, - user name equals John Doe at gmail dot com. - What you're saying is essentially select start from users where users chemicals John Doe. - There are very many other parts of the Jungle Query language, - which we will look at later, - which allow us to do more complex queries such as aggregations on joins and select - statements with Boolean operators. - The law required decorator, - which I had also mentioned before, - is an important tool in our arsenal for user authentication. - In our case, - we have the dashboard page, - and we don't want the user to get to the dashboard without looking in, - and we'll be using the long and required decorator to redirect somebody who has come to our - website and somehow is accessing the dashboard page. - We are It's Ural, - but it's not really locked in, - and we will redirect that person or that user back to the index page using the robin - required decorator. - So our next US is to log in and look out the user. - And this we would be doing in our index function where we have some placeholder court for - the same. - So going back to effect, - Senator, - this is that we had left it last way have put a comment in the index function saying he was - the registration or log in court. - What we're gonna do here, - or the logic that you'll follow is after receiving the user user name impossible from the - form we're going to find out if this user exists. - If the user does exist, - we will go ahead and authenticate and log in the user. - If not, - we're going to create the user. - So let's see how we can do that. - We already have our pedometers from the form in our request start post dictionary. - Now we have to retrieve them from there. - So what I can do is use earn income A pass for the first request thought post user name - gonna request start posed bus would if I do have user name and password and my request - opposed. - At this point, - they should be in these user name and password variables, - just in case they're not present. - For some reason, - I want to provide a default argument of none to the request. - Our force and this is missing a dot get method, - so I would get a none by default, - not going to check if the user input is present, - if not user name. - That means the user name is none or not Password. - That means I haven't received a user name and parts of from the farm, - in which case there's nothing I can do except to propagate this information to the user. - So I'm just going to return at a response in this case, - user name or password, - not present. - So at this point, - we have user name and password for sure, - since this court did not get executed. - Now let's check if the user is present in the database. - I'm trying to fetch the user from the database by its user name, - so if a user is present and I had to attend to get the user, - otherwise I will create the user. - In either case, - I need to log in the user now this. - Objects that create user method is taking three arguments. - The first is the user name, - and the second is the email. - And third is the passport. - In my case, - the user name and email are the same. - So I'm just passing the user name for bold authenticated actually takes user name and - password, - but I'm going to give these arguments by name. - This is something you've been doing Bip on. - If you do this, - you don't have to remember the order in which the arguments appear in the function. - So at this point, - either my user has been authenticated. - All has been created, - in which case I'm going to log in the user. - Are you think the robin function? - The long infection takes a request and the user itself now we haven't really imported. - The symbols tend to get Logan and log out yet. - So this is how we can do that. - We can actually, - important symbols and this matter itself in index. - But instead of doing that, - I'm going to do them here at the top again because I'll be using them in the log out method - as well. - And after a successful Logan, - I will be redirecting the user to the dashboard. - So let's test this out. - It says Local name User is not defined, - which is because I haven't included the use him model. - Let's try again and I got the dashboard. - How do we know that our user has actually being authenticated, - but we don't see any editors and say its form is valid. - But I would still like to see what actually happened here that create a new user or didn't - don't tend to get the user. - So for now, - I'm just going to Prince, - um, - put some print statements over here. - The other thing I'm going to do is in my dashboard template. - I'm going to print out the user name. - I'm just going to say curly braces, - open curly braces Open user because they use available is always a part of request. - How refreshing as he dashboard cities out of demon. - So that tells me that I am getting the correct user. - So let's try to log and lock myself in again. - Ressam it and let's see what the awkward is, - it says, - longing in user. - But I was already loved in, - so it probably did not know me in again. - It said. - But it did not say creating new user because I already exists. - Now if I go back to know slash index and I put a new user over here, - I'm gonna put just a random email address sitters out at hotmail dot com and see what - happens. - So we received an exception here called the Does Not Exist. - Exceptions. - So what is really happening is this, - uh, - user don't objects that get lying is throwing. - An exception does not exist because this user citizen and O'Quinn dot com does not exist in - our system right now. - So I have wrapped this line in a try, - catch block and try except broken Fight on and I'm catching. - The object does not exist. - Exception. - And if I get this exception, - I'm creating a new user user. - Don't object. - Still create underscore user. - So let's try again and see what happens again. - I have the user cities out of hawkman dot com, - and I press submit, - and this time I get dashboard sit, - Assad told me local So we have successfully created a user and Lageman, - we can check this in our secret light database being select, - start from all future, - so not BC to users over here, - set us out at gmail dot com and sit us out at hotmail dot com. - So this is never log in and sign up process. - They're still once that we need to complete, - which is the love out process. - So let's see how we can do that. - It's actually quite simple. - In your euros popular, - you can add a new function on new your old call about. - Actually, - we're going to all of you do a boat and not long out. - This is because log out of the jangle internal function so we don't want to give it the - same name of the view. - And the you are a slash love out and in our view, - so you I we're going to write the log off function. - We should simply call the jangle longer function. - Pass it the request. - Redirect the response to our index peak. - Now, - to involve this longer function, - we need a link on our dashboard that allows the user to love out. - So let's give a link here. - A trap equals slash north slash love out and let's test is up. - It says Do love out. - It's not defined because we named it Do love out what, - in my view, - have it a blowout. - So let's do it again. - Now I log on link over here, - I press log out and I'm not. - Don't know. - I convert him again as cities out a demon local. - And here I am, - and just so test that this is working correctly. - The science is loving and user and no new users created and begin again. - Verify that from select star from all tutor in our secret like prom, - I still have to users. - So this is your user logon and signing out, - and the next step for us is to start creating notes. 9. Generating forms and saving data via ModelForms: - in this lecture, - we're going to learn to create new notes and say them to the database. - So far, - we have London born models and forms We run what, - posting the quest, - and we've learned about saving data to the database. - Now, - using all these tools, - we can create new notes and say them to the database. - But Jackal can make our life a lot easier by a tool that provides called modern firm model - forms are very powerful classes, - which combined the part power of jangle forms and jangle models. - Let's see an example. - So this is what our not model looks like. - It has an owner title text and create time. - Toby ableto edit this note and add a new note from the browser. - We will lead a form that has the title text and the create time field. - We don't need an owner because the owner is going to be set to the logged in user at that - time. - So how would you go about doing this? - From what we have learned so far, - it would make sense to create a new form called the North from and pass it from in your - template and show it on the browser and edited just a baby at a new user. - The problem with the strategy is that we end up creating a replica off these fields that - have been specified in the model for exactly a north form should have a title, - a text and create time field. - And each of these will be from so charmed field form, - start chair, - feel for text and form start, - date, - time, - field, - date field for create time. - So this makes you repeat a lot of court and so much that we heard about jangles. - Dr. - Principle, - this example doesn't seem to follow it, - but there is a solution. - Jiang who has a tool called model forms. - I wouldn't pay some quarter We're here and I'm gonna say from jangled out forms import - model for what a modern form does is it takes as input Ah, - model And it generates a form automatically. - So all these fields, - the title tax and create time, - including owner actually will get terminated by Django for you using this morning form - construct. - So this is how you define a modern form and in the class not for him. - And I drive this loss or extended it from the class mortal form. - By the way, - just as a side note, - this is how you do inheritance and fight on. - You could write a class name, - open the bracket, - and then you can specify the name of the class. - Or you can also specify the name off multiple classes in a comma separated list if you want - to inherit from multiple classes. - But in this case, - I'm saying that class no form derived from model for uh then inside of that I have another - class called Meta. - A meta class is generally used to pass properties to a certain class. - So in this case, - I'm saying that this modern form called Not From, - comes from the model called Note. - So this is our north morning, - and this more informal generated feels. - Based on this note model, - and that's it. - I don't have redefined the title Texan create feels. - Now I'm going to pass this model into my view and from the viewer, - I'm going to pass it to the template. - So let's look at Dash four daughters. - Thiemo. - I have put this piece of court over here to find the table and row in the table and the - column in the table contains a form. - The farm is called note form, - and the action that the form leads to on submission is slash node slash dashboard. - The method is posed and this is our Sierra CS out of token. - And then I have formed on SP just the same way that we had done it for the long inform. - And then I was somebody but no here. - And this is just the name of the or display off the summit button, - saying New note. - Let's just focus on this column right now and forget about this commented piece, - of course, - which will come to a resource and not, - in my view, - stop. - Even in my dashboard function, - which had these three lines and I have added rollers coming, - commented court over here. - But let's not worry about it for the moment. - Uh, - I'm passing a new note form by creating it over here in my request contexts as the form - variable dashboard on East Yemen. - This is very similar to what we have done in the log inform for the index view, - and that's why I'm not typing the court as we go and then I have important some more things - from models I have imported note, - and not far. - So this is our new dashboard page. - Let's take a look at both Dash looks like when you hit it to the browser. - No, - instead, - off logging in normally, - as I would do to get to my dashboard. - I'm just going to use the euro slash node slash dashboard to get to the dashboard, - and I just want to see what happens. - But I was able to get to the dashboard. - I have a formal here now, - which has been rendered to the model form and my dashboard, - says Dashboard Anonymous user. - So if you're wondering why this is, - this is because there is no user longtime right now. - But our dashboard through this Ural is also accessible to a non golden user, - which is not a good thing because users that are not long and should not be able to get to - the dashboard. - After all, - this is a user dashboard. - How can we fix this? - This can be fixed by requiring a user to log in before coming to this you are, - and there's a very easy way to do that. - In jangle, - it's called a Logan Underscore required decorator, - So I'm going toe uncommon. - This line over here, - which is at Logan underscore required open bracket blogging underscore you are equal slash - node slash index. - What this Linus saying is required log in to anybody who tries to access the dashboard view - , - and if the person accessing it is not laden, - redirect them to the log in your own. - With in this case is our index page and off course. - I have to load the logging import. - The long and require decorator from django dot contractor ought don't decorators. - So let's see what happens now when I try to access the dashboard page. - I've just been oppressively fresh and by your own changes to slash no slash index. - Mexico's no slack dashboard. - So as you have seen, - I cannot long into the dashboard anymore. - Unless I'm locked in, - let me long in a citizen use my password, - beat a beauty and press amid, - and I'm here on the dashboard. - So a lot of requires a very handy feature of Django, - and it saves you a lot of work from actually checking if the user is logged in or not in - your view and redirecting the user. - It does all that for you, - so this form looks great. - This is a title for the note, - and this is the text, - and this is a create time, - and I can press a new note to create a new note. - But I also have this owner field and what modern form has done it since the owner in the - note model is a foreign key, - modern form actually access all the present users in the database and populated in them. - Inform off a selection list. - So I have sit without a female dot com and sit us out that hope me and don't come over here - . - This can be a very handy feature. - Let's say you had ah foreign key into another table, - which waas the tax table, - which are the applicable tags you can apply to your note. - This would be extremely handy in that case, - but in our case, - that is not that useful because we want to save the note for a particular user. - The user that has locked in right now so we don't really want toe. - I want someone to be able to choose a user to save a note, - so we should configure our modern from to somehow remove this owner field. - There are two ways of doing this and I'll show you one of them. - What you can do is you can go to modern, - stop you I and inside the meta class for the north form for your morning from you can add a - new fuel cold feels and you can specify all the fees that you want to exist in your model - for So I want that title. - I want the text and I also want to create it also create time. - So let's see what happens now I refresh and the owner feel is gone. - This is the first day of doing this. - But this is a bit cumbersome because if I just want to exclude certain feels I should not - have to enlist all the fields that I want to see. - So what I can do instead I can say exclude over here and instead off naming all these - fields, - I can simply say owner So I'm saying show me all the fields for the note model. - We have this model for him, - but exclude the owner field. - Let's see what happens down. - I refresh and the result is the same. - I don't see the owner field, - but it's much easier. - Died only one field. - So now we have the set up Toby ableto present no new note button and save the model form - into the batteries. - So let's take a look at the dashboard view, - similar to the index view, - have divided this matter into two parts. - Now the first part handles the post request and the second, - but remains the same but handles the get request. - So let's look at the more interesting part, - which is the handling of the post. - The first line is D equals requests that postal copy. - What I'm doing is I'm creating a copy off the request of post object. - The reason I'm doing that is because request that posed is a query, - said object and its immutable, - which means I cannot add or delete something from it. - And the reason I'm creating a copy is because I want to add the owner field to this request - of pose because, - as you might remember, - we had deleted the owner from our model form, - and so we don't have the information on who the owner off this note would be So I'm - synthetically inserting the owner field, - the owner key with the value off requests user i D, - which is the I d off the current user that I created a new form instance off the class, - not form, - which is our model for him. - And as a argument, - I'm passing to the note form constructor the D Dictionary, - which is a copy off our request off post with her additional variable owner. - This is a bad image rights, - our mortal form with everything that is president question posed, - which hopefully is the title text and created the next line checks of the forms valid. - If the form is not valid, - I simply to turn the dashboard dot html template again and I've passed to it the form - instance that I have just created. - But the form is valid. - I'm creating a note object by calling form, - not save, - but I'm passing Comet equals falls to it. - The reason I'm doing that is because note contains of foreign key, - and I want to set no dog owner to request a user which is the current user. - Only then can I say the note object database. - So the next line is no doubt saved, - which will actually persists this note into the database. - And once the notice saved, - I'm returning the dashboard, - have you back to the user. - So at this point, - I would know it should be getting saved to the database. - And if there's an editor in the form, - we should be getting back theaters. - So that's test that out. - I'm just going to refresh this page and let's try to enter a new note. - Let's name this class. - There's not a jangle class not, - and the next you're going to say We love learning jangle, - which I'm sure we all do and put a new data were here, - and I'm going to press new note now and see what happens. - So we have gotten back our dashboard page. - But first we still need to check if they're not actually got added to the database for - which I'll go to Sequelae Tree and I'll to a select star from notes underscore. - Not cynical and sure is Well, - we have this note jangle class note. - We low learning jangle with the date 13 7 2022 saved in the database. - That's right. - One more. - Now we have two notes both our general class notes and different tastes notice that the the - first feel that you see here as the primary key i d for the notes underscored no table that - has been generated by Django itself. - The second field is the owner, - and the owner idea, - in this case is number one. - So let's see who the owner is as you select star from all users. - Actually, - it's all user. - I see that there are two users. - The first user is with Primary Key one, - which is citizen out of gmail dot com. - So this is a user that our notes in this cold no table has a nose for. - And that's correct, - because cities are a demon dot com is the currently logged in user and is adding these - notes. - So now that we can save notes in the database, - our next focus is going to be to browse these notes, - to be able to edit them and delete these notes 10. Introduction to ModelFormSets: - In the last lecture, - we learn about modern forms, - a very powerful feature of jangle that helps you generate forms automatically from models. - We also know how to save new notes in a database using a modern form. - The next thing a user may want to do is to edit the existing notes in a database as well as - be able to defeat them. - So let's see how we can do that. - So before we come to a solution that's not formulate the problem more clearly. - The problem we're trying to solve is having a bunch of objects in database and being able - to modify and delete these objects. - There are several U. - S veterans that we can use to solve this problem. - The first pattern could be off updating or deleting one other time, - in which case you would have a row, - which represents an object in a database. - A single roll often object in a database, - and for each or you can have an editor delete button on clicking at it. - You might get a mortal up of dialogue populated with the fields for that role, - and you could modify an update one object at a time and Similarly, - you could have a delete link or delete button for each row on delete one at a time. - The second you I pattern that you can use is off multiple update and multiple delete, - which means that you see a table off creditable fields and delete check boxes next to each - role and you update multiple rows or delete multiple roles at the same time. - As you can see in this slight, - we have multiple rose that Easter has fields. - In our case, - each of the roads will be a note object, - and the fields will be the title texts and create time. - Now let's say you want toe update the first note and delete the 2nd 1 Then you would select - the second note by checking the accident relief column, - and you would edit the fields off the first road, - and then you would just press update So you're deleting the second note and updating the - 1st 1 on at the same time. - This is a pretty common pattern, - which is record ing in a lot of applications. - Now, - if we try to implement this ourselves either the first way or the second way, - it can be very tedious. - For example, - to implement the multiple update and delete mattered. - The first thing you would do is fetch all the objects from your database that is all the - notes and send them to the client side on the client side. - You would it read through each of the objects, - and you would generate HTML. - Alternatively, - if you're using jangle, - you could also fetch all the notes from the database and any attempted. - You can have four loops so that you generate the HTML for each of these rows on the server - side itself and then questi HTM onto the client side. - So in case you're using templates, - you would probably have a four do when you're a trading over all the note objects for that - user and generating the fields for each of the roads for Notre objects. - Now you're displayed the step that or these fields inside of a form on your client side and - your client can edit these fields. - And then he would press the update button, - which would do a form summit, - in which case you receive on the server site. - Many fields for many rose, - all of which may or may not have been updated, - and you would have to keep a drive off which off? - These have been updated on which of these have been marked for deletion. - That's a lot of logic to implement on your own. - And that's the problem that form sets and modern form sets sold for you. - Do you a good way to think about From sets and modern form set. - It's similar to how we think about forms and more forms. - So, - modern Form said is to a farm, - said what a modern form is. - Still far a farm and a modern from operate on a single instance off database object, - while a modern form said on a farm set operate on multiple instances. - So modern forms that really operates on the result off, - a query said. - Which means that when you do a query on database, - for example, - retrieve all the notes for a user. - This one we don't do your query set. - And on this, - Kuwaiti said, - you can create a model form set on creating a modern form set on a query said. - Not only will we be able to render the objects returned by this quality said on the browser - in the form of the table. - But we will also be ableto update them and delete them at the same time model form seven - providers and extremely powerful tool, - which will save us from writing a lot of logic for rendering multiple objects in a form on - a browser, - as well as updating them and marking them for delicious. - This is exactly what you want to do with the not objects. - We want the user to be able to see the note objects in the form of a table, - be able to modify them or marked for deletion and then present update button, - which will either modify the modified notes or delete the ones that are marked for deletion - . - In the next lecture, - we're going to go through some code, - which will show us how to use modern from sets. 11. Updating and Deleting objects via ModelFormSets: - so not that we have had an introduction to modern form sets. - Let's take a look at some court, - which will show us how we can use modern form Selves to update and delete multiple loans. - At the same time, - the sword require a change to the dashboard view, - as there is a dashboard template. - So let's look at the dashboard view first. - I have here replace the dashboard view with a function method. - Dashboard underscore. - Old I've simply renamed the Old Dashboard mattered, - and I've written a completely new dashboard view matter, - which is significantly smaller than the last one. - So let's try to understand what's happening in this new dashboard method. - So the structure of this method is similar to the last one in that it's divided into two - parts. - The part that handles the post request and the part that hundreds to get part of the - request. - So let's take a look at the part that handles the cat request. - The first thing I'm doing in that part is I'm creating a form, - said Object, - which is an instance off north form said. - So let's try to understand what a note forms that is at the beginning of the function. - I've imported a symbol call in line from some factory. - Now I have told you what modern form sets are, - but we never spoke about in line farm sets. - So what are in line for upset in line form sets are an obstruction on top of model from - sets, - and they will be used in situations when the model contains one or more foreign keys in our - case, - or using the note model, - which contains a foreign key to the user model. - That's why we'll be using in line form set, - because it will make life a lot easier for us, - and you will very soon see how so when I'm creating this new type call note, - form said, - and notice that it's a new type I'm using this method call in line forms of factory, - which is a factory mattered. - It takes the first argument as the foreign key, - which is the user, - and the second argument is the not the model itself. - This is because I'm trying to create in line form, - said that it straight through all the notes. - For a certain user, - the third argument is can politicals true, - which simply means that I want to support the Galician off these objects on my form, - and the fourth argument is extra equals one now. - What this means is that let's say the user centers are that gmail dot com has five notes in - the database. - Then my farm said my in line forms that is going to show me all these five notes, - allow me toe, - edit them and lead them. - But it will show me an extra line which is denoted by this extra equals one matter. - And the reason for this extra line is to be ableto add new notes from that same form. - So you remember how we had created a new form called the Note Form, - which was a modern form before in our old dashboard method, - to be able to create new notes and add them to the database when we're using in line from - set or model form sets, - we don't need to do that anymore. - The modern forms that will provide that functionality for us as well, - so not only can be update and delete existing knows we can also create new notes just by - using moral from sets. - So now that we know what a note forms, - that is, - we're creating an instance of the North forms in this line, - and we're passing it to its instance. - Pedometer request, - not user. - Now this is a very interesting and powerful light. - It is creating a form set which will contain all the notes in your database. - But how is it doing this in a single line? - So think about what's happening in this life. - Somehow the note forms that is, - retrieving all the notes for the logged in user, - which is requested user that it is creating a former of them. - And it is creating fields for each role, - which represents a not object. - This is some really powerful stuff happening in one line and since we're using an online - farm set and in light Form said knows what the foreign key relationships are because we - have provided them in the first and second arguments as user and note, - it knows that users of foreign key that is being used in North it is going to fetch by the - foreign key. - All the note objects from the database for that user that is being passed instance equals - because don't use her and it's going to create the form automatically for you. - All you need to do now is pastors Farm set to your template and let it render itself So I'm - using this new method over here called Render to response to create a template and render - it This is simply a jangle shortcut and it should be no surprise that it it is important - from the jangle don't short goods package rendered the response. - So what rendered a response does is everything that is done in thestreet lines over here. - It creates a new template using the loader simply because I've specified attempted name - over here. - It takes a bunch of very words in a dictionary just the way I passed variables in my - request context, - and I can possibly quest contacts to it as well. - So instead of using these two lines over here, - I can simply condense all this code using a render to response. - So this is what I will be using from now on. - But really, - the effect off this line is exactly the same as doing a template equals loader dot template - , - creating a request context and sending back in a CTB response. - When you're writing serious jangle court, - you'll find yourself using renders response a lot more. - So this concludes our review off the handling off. - Get requests for the dashboard matter. - Now let's take a look at the post in the post of my first line also creates a note, - form said. - But instead of passing it instance equals request a user. - I'm passing it. - Whatever I have received from the posted request, - the first argument is requested posed. - The second is requested files in our case, - because the files does not really have any significance. - But let's say you're a form, - but the users could upload a bunch off pictures. - In that case, - those pictures will be contained and requested files, - and the third argument is an instance equals request on user. - The next line checks if the forms that is valid so it will do all the validation. - Check just the way you would do them in a modern form or a plane or form. - And if the form is valid, - it's simply called, - the firm said, - not save method after calling forms that don't save all the a base that the user had made - in the farm. - In the template, - any deletions or any notes that the user had marked for deletion and any new notes that the - user had added would automatically be persisted to the database. - This is the power off modern form sets. - Now let's take a look at the attempted itself and see what changes we have to make a - dashboard or STM a. - So just noticed that I'm passing my farms that object as a template perimeter in my Get - Acela's My Post. - So this is my new dashboard dot html. - This spot has remained the same, - but I've created a new form over here. - It's still called the Notes update form it still doesn't cost and in most of Europe, - slash notes. - Life dashboard. - And here's my cross site request forgery token inside the farm. - Instead of having a new note form in a table, - I simply have this block off court. - The first line in this court contains in curly braces, - form said dot management underscore, - for this line is required because model from sets use something called a management firm - that manages all the radar present in your forms. - For example, - how many total feels do you have in such? - The next line is a for loop it trading over the forms of itself, - and it sees for every form or for each form president of form said. - And you can think of a form as a single note or a single row in your database. - And next time just putting out all the fields that are in my Lord, - the 1st 1 is formed that I D, - which actually will not get rendered on the farm because it's an auto field. - The second is formed a title, - then the form, - the text and the former create time. - And finally, - I have formed on the lead over here, - which will actually render as a check box, - which I can check to delete a particular role. - Remember that one node represents one note and then I haven't end four tag and finally I - have myself in button with the value of update, - and that's my form. - That's all I need to do to be able to edit and delete multiple notes as well as at a new - one. - So now that we have all these plumbing in place, - let's see what the space looks like. - But I'm pretty sure so far all the sense fell like magic to you. - So let's see how our new and improved dashboard baked looks in the browser. - So I'm going to hit the euro notes, - slash dashboard and the store looks like I have this new farm which contains the title of - my notes, - and it contains the text of my notes. - So you remember we had two notes. - One was we're learning about tango about modern forms, - and the second was below learning jangle. - And then I have had a create time associated with these two notes. - So I'm able to see these two notes in the database, - and I have this extra blank line over here. - So you might remember that extra equals one perimeter. - Let me just jump back to that right here. - And this is the part that causes this extra lined up yet over here. - So if you want to see how easy is it to add a new note? - Now let's add a new note that's called a jangle class. - Not to Let's see. - Form sets are very powerful. - Let's put a date over here and press update. - Believe it or not, - this page just reloaded. - And now I have three notes in my database and If you just want more proof of that, - let's hit the You are a no slight dashboard again and this is what I get and had this extra - line now And this is my new Nord. - Now, - if you want to play with delicious, - let's start with the lead the 1st 1 that says We're learning about modern forms Press - update and it's gone. - Now let's add another Lord I'm gonna call a general class nor three I'm gonna save old - inform sets feel like magic. - And just for convenience, - I was just, - uh, - copy and paste the date from here and press Um date. - Now I have three notes. - I'm going to change us text of this toward note, - which is more informs that feel like magic to model France worked like magic. - And I'm going to delete the second note which which the title of which is Django class not - to. - So I'm doing these two actions at the same time and I press update the jangle class not do - is gone. - And my jangle blast No. - Three say's modern form sets worked like magic. - So I hope you have witnessed now what the power off modern form sets is, - and in general, - about the power of Django ways that it can let you do such complex insanity, - for which generally you would have to write a large block, - of course, - and some very complex logic to manage all the fees that are coming in your request are - opposed and to remember what needs to be updated, - what needs to be deleted and then execute that correctly on the database side as well. - Jang Go's mortal from sets are helping you avoid writing any off that court and doing that - for you in a very, - very simple way and intuitive way. - Once you want to write two or three more water from the examples, - it will be much more intuitive to you. 12. REST APIs in Django via TastyPie: - hi. - As we have come towards the final electors of the scores, - we will talk about something called Rest and Testify. - Now, - before we get into Tasty by, - Let's Stop a little bit about rest and why rest is needed so rest is short for - representational state transfer. - This term came from a paper that one off students, - a PhD student, - brought back in probably early two thousands for its Does it visitation. - And it became very famous because it gives very coherent set of guidelines and rules for - programming something called Arrested here, - which is a way to access remote resources and to update them or delete them over the - Internet. - So in our notes application, - we have a webpage that does access Remote Resource is, - in our case, - the resource being note or the notes itself, - and we do update and read notes, - and we're not using any rest. - So why do we need rest at all? - Well, - there are a couple of reasons. - Think about somebody using the notes application on a Google glass interface and gets a - Google glass interface. - You probably don't need to or don't want to show the user exactly what the notes up looks - like because the interface for that would be unusable on something like Google Glass. - Google Glass probably has a different user interface layer that would want to present knows - in a completely different thing, - maybe providing a touch interface and the way we have designed it. - With simple a steamy text, - boxes may not be am unable to something like Google Glass. - So one thing that you can do in this case is instead off, - rendering the notes on a Web page simply provide the notes as raw data. - So instead off showing an HTML page with the content of the notes. - When somebody wants to get they're not, - you can just provided as a stream of data and the data can be included in something like - XML or Jason. - So that's what all the use cases, - the other use cases. - Let's say somebody wants to implement some more advanced mortality on your notes. - For example, - some sort of natural language parsing or let's say, - the notes APP is being used by someone like a stockbroker who is putting financial - information reports in the North, - and another person wants to write of service for accessing the notes and digging out or - digitizing this financial information. - Oh, - are scraping this information from the North, - but our notes a P I or notes application does not provide that. - So what we can do is just provide the notes to this other service that wants to scrape the - data in the form of raw data instead of exposing a user interface. - So in such cases, - when we have to provide raw data, - it is very useful to use the rest interface because it's something that is universally - accepted on applications. - Know how toe receive data of your arrest, - and it's much more intuitive for them. - And once arrest interfaces provided a lot of applications a lot off. - Other dragons can be used to access his data and play with this data. - So that's that's why less is very useful. - We can provide a single rest interface which different mobile devices or laptops or - browsers or any kind of devices can come and access. - And once we're exposed, - our data in the form of rest, - a lot of services can use our data and utilize it for purposes that our service does not - right yet, - So we become sort of like a data provider. - So the representational state transfer is an architectural modern for accessing or - modifying the sources over the Internet. - There are a few main tenets off this philosophy and, - uh, - a very important and it is being stateless. - So the server should be stateless, - which means every request that close to the flight should be independent off any previous - request. - It should not be dependent on it. - It should contain all the data that is needed to process his request, - and another important principles is cashing. - And the server should be marking any resource as catchable or non casual. - And once the resource is mountains catchable, - the client which may be the browser the mobile device, - has theater authority to cash the data on the client side or that resource on the client - side. - There are other important things about rest that you can read in this paper, - which I put in the references in the end, - and I highly recommend you read it. - So what is tasty by testifies this jangle up, - which can be installed in the jangle, - and it provides us most of the plumbing to provide a rest API I so we don't have to do or - implement that logic for writing you are else, - which are which looked like a rest interface on making resource is out of our models or - authorizing resource is for access to different bodies. - So these are some of the things that taste, - if I does for you and also in courts your resources into Jason or excellent for you. - So any jangle model that you have written, - for example, - the North moral or the user model you can expose using testify as a restaurant, - a phrase which makes tasty by very useful because you get away from writing separate euros - for your resource is and you get away from writing and including layer into Jason or - external for your resource is. - So let's take a look at what's required to set up testify. - So they installed a steep I on most UNIX based systems. - It should be easy enough. - You could just do pip install Django hyphen, - tasty pie, - and I provided the link from, - but you can download testify on Windows two. - It should not be much difficult once you don't know the tasty by source code. - You can run, - fight on, - set up top, - and if you have any problems with this? - I'll be happy to help. - And after installing testify, - you also need toe of data installed abs and your settings up. - You I file for the notes up and add testify The string testifier to install ups so they - stick A is actually just a jangle app which provides you several functions functions. - And finally, - you need to run, - fight on Manus. - Stop people in sync TV. - So you need to run sing db as you run for other tables when we had a new model. - So I hope you remember that every time we add a new model or a data model, - we have to run sing db to get our database tables and sink with our bike lunch. - Django, - our models. - So again, - tasty pies an application. - And once it's put it installed apps, - it will create a couple of tables for you, - which will be its own housekeeping tables and militar and single be for that. - So these are some references. - And now we're going to look at some food and see how we can convert notes into resource is - that are accessible, - be arrest. - So I already written this code but there's really not much to right, - so I'll just go over it. - So the first place we need to modify is our model stop you. - I file for the North application So absolute slash north slash models DePuy and have added - a few lines here. - So the only thing I'm doing it I'm exposing my note model as a resource tasty party source - . - So included these two packages here testified or authorization authorization and something - called a modern resource, - which is one of the core packages or core classes. - And I've created a new class called No Resource, - which extends or inherits from model resource inside that I have a meta class and this - query said member of the middle class contains or is assigned to. - Not that objects are all, - which means it will have access to all the notes are not objects. - So as you remember, - also, - you might remember the objects that all matter off. - The jangle query language will basically retrieve all the object from the database. - All the note objects from the database so assigned toe quit, - he said. - This query and this is to let's the Morning resource or the note resource know how to get - all the note instances from the database that I've given it a resource name. - Call note. - But you don't have to give this resource name by default. - Testify will generate a resource name, - and in this case it will. - We know. - And finally, - I have given it a new authorization. - Instance. - Now this is the most basic authorization instant. - But in practice, - when you are doing this operation, - you should use a more sophisticated authorization. - Class will testify, - so there's no doubt objects that are all assigned to query, - sir, - is really how there's no resource knows before is the resource that it is exposing on - managing. - So once we have done this, - let's go to you on stop you that there are a few changes and you are a stop. - You first. - Is I'm important. - The package FBI or the module AP I from tasty pilot, - FBI and second leave of ah important note resource, - which we just created Next. - I have assigned to the variable V one underscore a p I an instance of Class A P I and given - a diversion or name even. - And then I have this line, - even a piano register no resource. - So I'm registering a new resource with a new A P. - I called even a P I. - Now finally, - I have added to my euros that people filed this line. - Anything that starts with f B, - I should read right toe even underscore AP. - I don't you our roles and we will underscore underscore ap. - I don't Urals are some euros that are being generated by tasty pie for you and we would - just see a demo of how that is done and this is all. - You don't need to do anything else and let's see what the result of this is going to be. - And to remember the run managed people icing Devi. - So when I had run sing d B, - this is what thing BB had given to me as the output ex creating two new tables tasty by - underscore FBI access and tasty pie underscore a key Stacy I would be using for its own - housekeeping. - So please remember to run the step. - I'm gonna stop my supper and now I'm going to access a euro. - Now this you are 11. - Accessing local host Colin 8000 slash notes slash ap I slash everyone slash note. - Question Mark former equals Jason. - Enter and see what we get here. - We are getting some meta information. - Total count. - That means we have to notes here and then we're getting objects and this is all Jason - encoded. - And there are two objects here because we have two notes in our database, - and they're all the fields for knows the create time. - The i d feel the resource you are either is how to access this specific note object. - And there's some texts we love learning jangle and jangle classman, - and you do such notes because we have to such not in the database. - And this really is all you need to do to expose notes or any other resource with testify - off course, - you need toe do some more things, - such as bait, - your authorization settings. - And if you don't want to expose some, - feels like the I d feel, - and you can put in the extrude list for your resource and testify will not expose this - field. - So for that you would I can point you to the tutorial, - which is actually in the references in the presentation, - and you can read It's very simple two or three pace tutorial off tasty pie on. - I really help you go along with your buildings. - Rest a PS for exposing your data. - So let's just try to retrieve a specific note. - So what I'm gonna do is I'm gonna say no slash ap slash b one slash node slash six, - which is the idea off are not in our database. - Question mark for medical Jason and I only get this not this time the specific knot and I - don't get so this is just to get command, - but I can also posted update data, - and I can also use put, - which is similar toe post. - But it's actually quite different. - And there's there's quite a lot of debate on the Internet as to when should we use in a - city? - People's worst? - Http put. - And one of the guidelines you can follow to figure that out is if you're running a command - or accessing or updating a resource in such a way that hitting that you are multiple times - will not change the result or make it any different, - then hitting the Ural only one time. - It's an example of that could be updating a field to a specific value. - So, - for example, - if you're updating your, - uh, - date to today's date, - then that's an example off, - I'd impotency, - which means that you're updating the create create timeto UH, - 9 p.m. On January 1 2030 that you can keep doing that operation again and again. - The data time will always remain 9 p.m. January 1 2013 Once you updated for the first time - , - as opposed to let's say you're implementing the date every time that you're hitting the - euro. - So let's see. - Initially, - it is July 27 2013 and you implemented ones it becomes 28. - Then he instrumented again and become 29. - So in this case, - this inclement operation is an operation that changes the resource every time. - In that case, - you should be using opposed. - So this concludes our discussion of lesson testify, - and I hope you find this useful because I certainly do 13. Django in Production, caching, scaling and other topics: - Hi. - We have reached the conclusion of this class on in the spinal lecture are recovering a few - topics that we have left our and I believe they will be useful to you. - So let's start. - Let's talk a little bit more about jangles query language. - We have seen the simpler things that we can do it the query language. - But there are some more complex operations begin to you as well. - For example, - there's a filter cross using which weaken do searches such as Find me all the North Officer - title starts but tangle. - So what he would do for that is the first line here. - Slide, - no doubt. - Objects that filter titled Underscore Underscore starts with equals angle. - This is similar this using a wear clothes and sequel. - The second line says no tone objects are all and in brackets golden. - Five. - This is taken to using the limit five clause in sequel, - which means you're limiting the output or number of records you're fighting. - 25 Then there's another example of note on objects of filter revere passing. - Create time. - Underscore, - Underscore lt and Healthy Eastern's for less than equal toe. - Similarly, - you can you greater than equal toe other operators. - So if you're looking for all the knows that I've been created before or at the date 13 7 - 2023 you would be using this. - And this is similarly using a sequel statement. - So let's start from notes, - not where create times smaller than equals 2037 23. - You contain multiple filters together so you can filter a query, - and then you can apply more filters on the filter query. - With its called Filter Training, - you can use the order underscored by clause as well, - and this is similar to the order by a sequel. - The minus sign in the field name indicates you want to order by descending to have a secret - . - Like aggregations such as some Max count. - You can use the close it as Notre Objects are all don't aggregate and then passing the - function, - such as Max on average and the field name that you want to agree it. - Similarly, - you can say no to, - or objects are all. - Don't count to do a select counselor off sequel. - Finally, - when you're facing some really complex queries, - you can always use the raw sequel function, - which can be used by saying model that is, - no objects are wrong and passing is your loss equal as a string, - so you can always fall back on Ross equal and still use some aspects of jangles warm, - such as getting the roads translated directly into objects while using cross equal. - I have talked a little bit about tempted inclusion and inheritance, - but I never gave you an example of how to use it. - So we're going to look at an example off temperate inheritance now and also go to through - some of the basics of template inclusion. - So if you're trying to give your website a consistent look and feel, - then you may have a header and a footer for a page, - and you have a west pain or least pain as well. - In such scenarios, - you don't want to replicate this cold for the header foot are resting the Spain in each of - your pages. - What you can do is you can write a base template, - and then you can inherit your templates from the waist up it, - and how you can do this is by in ST Extents, - based on HTML in curly braces and percentile symbols in each of Dr So that's looking an - example. - I wouldnt a simple template here called Based on East Yemen, - which contained some the basic HTML tags on. - I've also included the style sheet over here, - which I will come toe very soon and inside this inside the body of this based artist him - and there's a header but says he also notes up, - and there is a curly brace percentile block space content. - The Black Bloc is ah jangle temple. - Keyword and content is just a word that I I'm using to indicate that some content goes over - there. - But you can also call it. - You can call it whatever you want. - You can call it my content, - your content and finally I'm ending the block pricing in block. - So what happens when I extend another template from based on the CTM? - Is that everything except for these block closes comes through and then I can, - in my direct tempted implement these block closes so the contents of the base or East - humans block will be replaced by the content block off the drive. - So let's take a concrete example in the notes up. - One can imagine that dashboard or html and some other pages would require Ah, - header and footer. - So what I have done in dashboard or HTML is I extended it from the base stories team of - dumping, - So I used his extent statement Over here, - curly brace percentile extends basically steamrolled. - And after that, - I have curly brace percentile block space content just like ahead in the base template. - But now, - inside the content, - I actually do have something. - I have all this stuff that was happening before in Dashboard Oresteia, - Emma. - And then I haven't en bloc. - Let's see what the result of this is. - So we see this the awesome notes apple here. - And if you go to the footer, - we see the two Ling's about us and block. - If you would like to see the same on your index page, - you can do that as well. - So let me log out. - So right now you don't see my awesome notes up and the links on the index page I'm going to - copy and paste the extension of attempted on the index patient And here you go. - Now you have the awesome No tap the header and a footer on the next page as well, - so similarly, - you can extend all the pages that you want a header and footer Iran from your basically - steam attempted. - Now there was some more changes. - Human notice on our dashboard Bates. - So we're just going to go through them. - The one thing you may have noticed is that I've changed the text feel to a text area from a - text input. - That's because this is Tex and it can be a lot of tax, - so the user might want to look at it as a text area and how we can do that. - If you remember, - we're using modern form sets toe render. - These feels so. - What you can simply do is when you are creating your model form set, - you can positive form, - which will be our model. - From that we had written before, - we were using more reforms that so to my in light forms a factory and passing the another - argument called form. - And I'm passing in the class note form, - which is my modern form, - that I didn't at some point when I was not using water from set and to my note form. - I'm passing this new widgets argument in the or instance in the middle class and what I'm - telling which it is that for the text field off my model, - I want to use a special visit text area and the attributes of a text area are 60 columns - and 10 rows. - And that's the reason that you are seeing this text video here. - Finally, - you may have noticed there's this black border around your text inputs, - and, - uh, - button has changed a little bit inside. - It's whiter and has a blue tax on it called update. - So for this, - I'm using a CSS. - Obviously, - this is not very pretty, - but this is just the time off some basic CSS off using the tangle. - So I've written off CSS File North Sort CSS inside a directory called Static Inside of - Notes. - So not slash statics last year says directly has no sort CSS, - and the interesting part is a settings up your I file and how we have to change that. - To be able to use the CSS. - If you look in base or html, - I'm using static underscore you are ill. - The benefit benefit of using study underscore you are to serve static files or point to - static files is that I don't You have to use exact part over here. - I don't have to say slash node slash static slash CSS slash no stuff CSS. - I can simply say static underscore Europe and jangle would know where to get the static - you're off static file from. - And how Jang, - who knows about that is my specific. - A few things in the settings up your file. - So the first thing out putting here is thes two statements Import OS and I have just - created a variable called Based E I R. - Which is a base directory, - which will be the directory in which my settings are purify lies. - And this my statement will give me the base directory. - Now, - if you go a little bit further, - my static, - you are a list last static. - And then I added, - This entry in my static files underscored the IRS double, - which is always the part or join. - So I'm joining busy IR with notes less static. - So I'm telling jangle that's my static files. - Lie in all the entries inside of static files underscored the IRS, - and one of the entries is in basically I r slash notes slash static directory and busier - slash No. - So static has a CSS directory, - which has C S no Socso file. - And that's why I'm using static your own here and the season's directory and no soc Aceh's - . - Now, - if you have another application or in your APP suite project, - you can create another three static inside of that application, - and you can add it to your settings of people. - I static euro starting the IRS and when you're using, - study your URL. - You can access that file as well from that application, - so you don't have to specify the application name over here. - This just makes it much easier for you and makes you a corner lot more portable in case - you're changing application name or directories or the location of your static files. - Doublet inclusion is different from inheritance because we use the curly brace personal - include directive and gives a template name to include attempted and the include attempt - that might be a court snippet. - It might be a common rigid that you're using, - or maybe just a bunch of files, - and I usually use include directives to simply write a bunch of files over here like static - files. - They could my Java script in my CSS files, - they could be a part of a equally plugging I'm using. - And if I'm using this plugging in different pages or different abs, - I can just make one temple on keep including it on top of my XML file so I don't have the - right. - But for these wells, - over and over again, - so intemperate inclusion is simply a way off, - including some sort of HTML template cord jangle template code inside other templates. - Let's stop a little bit about how do you run sanguine direction? - So far, - we have been using Jangles Development server. - But one of the most popular ways off using Django is using a party to embed the jangle - framework in and using whisky, - the Web server Gateway interface, - to have a party in Django Framer talk. - You can read some documents on it. - There's an excellent extensive documentation and a strong community available for that. - But what this would in require is to download the more underscored, - abused by plugging and loaded into a party and then modify the apostle configuration file - toe include whisky configurations. - And if you read these documents, - that will become clear to you it's Ah, - it'll require a little bit off reading and configuration, - and I'll be happy to help you. - You're actually deploying jangle direction now. - How do you scale a jangle website? - If you're using a party with jangle party gives you the option off spawning multiple - processes. - And that's the most popular way off scaling Django. - You can also use multiple threats in addition to multiple Prosise, - and that's that's another way to do it. - I usually use multiple processes but not multiple transfer process. - So I only a single credit process. - And I have a party configured in such a way that it brings up and down the processes as the - load increases in correction. - When you're serving static files, - you might want to do it from a different location. - For example, - if you're using a party, - you might want all your static files for all your applications. - Store in a single location and be served from there because nobody needs to know where you - serve it from, - and you don't want to serve static files from your court cases. - You want to serve it from a different central location. - Usually, - people put the static files in on a UNIX system on slash r slash www slash local host and - so on. - So to do that, - you can use a command that jangles manage. - Don't be. - Why script for it? - You? - It's called Collect static. - What collect static would do for you? - Is it foot? - Collect all the files that have changed all the static files like like CSS JavaScript - images and would place them all in a subtle directory that you ask it to places which can - be specified where your we have one of those settings top you I configurations. - Let's just quickly take a look at that so you can use a static route configuration of the - settings up your I file to specify what your central location for placing static files in - is. - And then you can run the collect static command off the managed opioids. - Clift, - a second popular way of serving static files, - is by using a reverse proxy to Apache, - for example, - something like the ending server. - The advantage of that is that you're serving only a static files from one Web server like - engines while you're serving all your dynamic content from a party, - and that takes a lot of load out of awful party because Index is much more lightweight. - Innovate serves files, - so you're stratified. - Requests are going to engines, - and that takes a lot of Lord off a party's back. - Jangle provides a lot of tools and mechanisms so that you have to worry less about your - site security. - Let's go over some some of the security mechanisms. - The 1st 1 is secret injection protection. - The way you use this is by when you using Ross Equal query. - You can. - If you remember, - we say Model named or objects that wrong. - So, - for example, - no. - Don't objects are wrong and deployed. - Rossi, - quit quitting, - sometimes in your secret quit. - You wouldn't be taking input from the user from a form, - and you will be replacing parts off your sequel statement with the user input. - For example, - if you're searching your notes for any no, - starting with whatever the user is written on a search box, - then you would think the input from the search box and replace it in your query. - Your wear clothes. - Now ah, - militias user can use this sort of form input toe. - Give certain arguments, - which can do bad things to your database in some cases, - they can drop your tables or insert monitors things into your table. - So these are called secret injection attacks. - But if you always use jangles, - object that romantic and instead off, - replacing your query or con coordinating your query. - Cory's were close with the user input if he used the Haram's argument off the Romantic, - which is a couple or a list, - taking the user input and methodically replacing the important the sequel Query Wherever - finds a place holder like a question mark. - By using this method, - you can avoid secret injection attacks, - and I strongly advise you always use this method rather than con coordinating user input. - Your sequel Close. - The second mechanism that we have looked at before is the C s out of token, - which is used for avoiding cross site O R. - Preventing cross site request forgery attacks. - Also, - jangle does have excessive SSN on a CBS support, - which you can easily use on, - uh, - provide authentication an encryption when you are also Jang who has the SSL and https - protocol support, - and you can also have secure cookies in jangle jangles provides you several cashing - mechanisms. - So in case you have ah request that contain it takes a lot of time to fetch from the - database. - You can cast a request. - There are several kinds off cash is provided, - and the way to configure it isn't settings up your file. - The other Caches Dictionary Caches dictionary is similar to the databases dictionary in - that it can contain a default cash, - and it can have other caches as well, - so you can have multiple cashes in tangle now, - looking at example, - over here, - the way you configure it cashes by providing a back end. - So you're providing a back end. - Which tells you, - what kind of cash is this? - And the location for that cash? - So in Goetzel, - flat file cash like the jangle dot co dot Kashtan back in the file based on file base cash - , - you replied, - providing the location of flat file. - So in this case, - it's very time jango cash So jangle used this one as a cash cashing objects and jangles - Very easy. - You simply used to get and set matter of jangles cash. - So you say cash don't get on the key to get the object in the cash, - he said. - Cash not set the key in the value. - To put the object cash you have database, - find system, - local memory and meme cash options available to cash your data off. - One thing that keep in mind is when you are running genuine production were party. - You have multiple processes that you might want to use. - The file based man cash or database cash and not the local memory cache. - Because if you're using the local memory cash and cashing a request, - are the content on T the results of requests? - Then it's not necessary that the next request from the same user that wants to utilize the - cash data would come to the same instance. - It might go to a different process, - which were not not. - Have your catch it available in case of a local memory cache. - So with this, - we conclude this lecture and this class, - it's been a pleasure teaching this class on. - I want to read rate that I am available in case you hit a stumbling block or if you're - using general direction and whether it be a topic that we have covered in this class or be - something outside off it. - Rated Django or Fight or I'll be happy to help you. - So please feel free to send me an email or right on the sculpture forum to contact me or - please to follow me on Twitter as well, - because I'm frequently posting updates and logs over there. - So again, - it's been a pleasure teaching this class, - and I'm hoping to see some great back. - It's built on Jang about you. - Thank you.