# Python Django Tutorial: Full-Featured Web App Part 7 - Login and Logout System

## Метаданные

- **Канал:** Corey Schafer
- **YouTube:** https://www.youtube.com/watch?v=3aVqWaLjqS4
- **Дата:** 31.08.2018
- **Длительность:** 31:16
- **Просмотры:** 492,563
- **Источник:** https://ekstraktznaniy.ru/video/12138

## Описание

In this Python Django Tutorial, we will be learning how to create an authentication system for our application so that users can login and logout. We are also going to see how we can restrict certain pages so that users must be logged-in in order to access the page. Let's get started...

The code for this series can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Django_Blog


✅ Support My Channel Through Patreon:
https://www.patreon.com/coreyms

✅ Become a Channel Member:
https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join

✅ One-Time Contribution Through PayPal:
https://goo.gl/649HFY

✅ Cryptocurrency Donations:
Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3
Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33
Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot

✅ Corey's Public Amazon Wishlist
http://a.co/inIyro1

✅ Equipment I Use and Books I Recommend:
https://www.amazon.com/shop/coreyschafer

▶️ You Can Find Me On:
My Website - http

## Транскрипт

### <Untitled Chapter 1> []

hey there how's it going everybody in this video we're going to be learning

### create an authentication system [0:02]

how to create an authentication system for our django application so that users can log in log out and we'll also set it up so that users need to be logged in order to access certain pages so let's go ahead and get started so in the last video we saw had to create this registration page where users could create new accounts but they're not able to log in using those accounts yet so the admin page that we've seen in previous videos is only for users with admin access but by default our new users aren't going to have that so we need to have a login page for them on the front end and Django has a lot of this functionality taken care of for us on the back end already now I'm going to go ahead and get started by using their default login views so first of all I'm going to import these login and logout views within our projects URLs module so within our project let's go open up our projects main URLs module and this is where we have our admin and register route and also our default route that goes to our blog URLs so within this URLs module I'm going to import some views now these are views that Django provides for us for logins and logout so to import these we can come up here and say from Django dot contribute those views and we want to import those as auth underscore views now I mentioned this in one of the previous videos but any time you import views we're importing multiple views here into these URLs so you always want to say as and then call it something else so when we imported views from users we called those user views when we import them from auth we call them off views that way those names don't collide okay so once we have that imported then we can create paths for those views so I'm going to copy our register path here as a starting point and paste this in and actually let me just do one of these at a time so let me remove that okay so now

### create a login [2:01]

let's create a login view so I'm going to here so the path will just be to login and now we're going to use these auth views that we got from Django and this is going to be off views dot login view and look at the casing there that is camel case with that capitalized and now we want to say dot as underscore view and then for the name here we will set this name equal to login so now I'm going to copy this and do the same thing for a log out view and I'll explain this more in just a second after we get these in here so I'll call that log out the view is going to be log out view as view and then the name will be log out so this log in and log out view here these are class-based views now we haven't seen class-based views yet but we'll make some of our own later in the series so the built in views for log in and log out that Django gave us will handle the forms and the logic and all of that stuff for us but it's not going to handle the templates which is good because we want to make the templates

### match the look and style of our current web site [3:05]

anyway so we want them to match the look and style of our current web site so let me show you what I mean by this so if we run our dev server and then go to our web site so our dev server is still running up and it looks like we have an error I misspelled Django on one of these imports so fix that save it see if our server is now running it is okay so now let's go to that login route that we just created then we can see that when we go to that route we get this template does not exist error and these Django errors are extremely useful when we're in debug mode because they can point us in the direction of what changes we need to make in order to get things working so the error that is showing us here is that it's looking for a template and you can see here this is a little small but it says that it's looking for the template at registration ford slash login dot HTML so that's where that Django login view looks for that template by default now we could create

### create a registration directory inside of our templates [4:03]

a registration directory inside of our templates and create a login dot HTML template there but I think it would make more sense just to have our login template inside of our user templates alongside our register page that we've already created and we can tell Django that we would just like to look there instead so let's do that okay so to do this I'm going to open back up our URLs here at the end we can tell Django where to look for a template and we're actually going to pass this in as an argument to the as View Function so within here within this as View Function I'm going to say template underscore name is equal to and then a string I want to say that this is in users ford slash login dot HTML now we haven't created this yet but we will in just a second but for now let's go ahead and do the same thing with logout so I'll say template name is equal to and then we'll change this to logout HTML so now if we save that if we go back to our browser and reload this then we should still get an error but now it's telling us that it's looking for this template in users forge slash login dot HTML so let's create that login template inside of our users templates so let's open up our users app and navigate to those templates and within our users templates let's create a new template here and I'll call this login dot HTML and that's in the same location that our current register template is located as well and within this login dot HTML template we're gonna make this very similar to our other outs where we're extending the base template and we also need to display the form that the login view will be passing to this template now this will be very similar to the register template that we created in the last video so I'm just going to use that as a starting point so I'll open that up and copy it and then paste it into our login template so I copied the register template there and paste that in to the login template so in this template we're simply creating our form and our form has a field set and a legend and then we are displaying the form with those crispy form tags that like we saw in the last video and also we have a submit button down here that says sign up so we're actually going to want to change some of this stuff around so we're gonna want to change the legend this is now the login page so we'll change the legend to say log in and we will change the submit

### change the submit button to say login [6:28]

button to say login and also we see a link down here at the bottom that we had on our register page that says you know do you already have an account well if you do then you can sign in here so just like we did on that register page you also see a lot of websites where they'll have a link on the login page that says do you need an account before you log in and if you need an account then you can sign up here so instead of asking the user if they already have an account and to log in we will say need an account and then we will send them to the register page so sign up now currently this link here is dead because for our register page we didn't put an

### put an actual link to our login page [7:08]

actual link to our login page because our login page didn't exist yet but it exists now so we can actually feel in these eight reps so that these links are active so let's fill this in with URLs to our register and login pages so I'm currently in the login page and we'll link to the register page if they need an account and we saw how to do this in the templates video but if you forgot we can simply open a code block here in the href and just use this URL tag and then we want this to be a URL for the register route and within the register page we want to link to the login route

### link to the login route [7:44]

so I'm just going to copy that go back to our register template and now that our login page is going to exist we can fill in that href and say that we want this to be the URL for login and save that so now let's go back to our login page okay so now we have our login template done but even with this done this probably still isn't going to work in the browser so let me save everything and then reload this and the browser okay so we can see that we're at least getting a login page here now this login page should be somewhat functional right now so if I enter a username and a password that doesn't match any users in our system then it should be invalid so if I just say bad user name and then some gibberish password and then try to login then it says please enter a correct username and password so we can see that we do have some functionality here so that's good now I say that it's only somewhat functional because if we try to log in with a correct username and password then we're going to see another error so let me do that so I'm trying to try to rely in with that core EMS user that I created in the earlier videos and if I log in with that then we can see that we get a 404 error which means that it's looking for a route that doesn't exist now this isn't just a template that doesn't exist but it's trying to access a URL that doesn't have a view attached to it and the URL that it's trying to access is this ford slash accounts ford slash profile now

### add a profile route to our site [9:13]

we're gonna add a profile route to our site soon but right now we don't have one and even if we did I don't think I want our blog to redirect users to their user page when exactly when they login I think would be better if they got redirected to the home page when they logged in so the reason that this is trying to direct us to the accounts profile page is because Jango set it up so that when the login is successful it tries to navigate to that location but we can modify that location using our settings so I'm going to open up our project settings so let's go to our

### open up the settings dot py [9:48]

project and open up the settings dot py file and let's just go all the way to the very bottom here to create a new

### create a new setting [9:53]

setting so here at the very bottom I'm just going to create a new setting that is login underscore redirect let me spell that right redirect underscore URL and we'll set that equal to blog dash home and that is the name of the path that we gave to our blog homepage so now with that in place if we go back to our browser and try to log in using a correct username and password so I'll go

### log in with a username and password [10:24]

to the login page and log in with a username and password that is in our database then we can see that now we get redirected to our blog home page so that worked now this is actually logging in our user into our website so there isn't much visual feedback right now that tells us that we're logged in but we'll fix that in just a second but we can tell that we're currently logged in because I logged in with the account that has access to the site's administration page so if I go to ford slash admin then we can see that we're already logged in so now let's try to log out and then log back in so now if I log out and go to this admin page then it's asking us for a login so we can't access this page until we login again so let me go back to the login page that we just

### log in with those credentials [11:13]

created I will log in with those credentials and then go back to our admin page and I'm logged in again so that login page that we've created is working even though it's not giving us much visual feedback at the moment so now that we have our login page working let's change our register route so that users are redirected to the login page after they login now currently if we look at our register views so let me pull up our user views here then we can see here that after they have successfully registered the user that we are giving them this success message and then redirecting them back to the home page but it would make a lot more sense

### redirect them to the login page [11:55]

right here to redirect them to the login page now that we have this working so that they can log in with their new account and make sure that their account is working so let's go ahead and change this so for the message I'm just going to get rid of our current message and say your account has been created you are now able to log in and now instead of redirecting them to the blog home page let's direct them to the login page so I'll save that ok and before we view this back in our browser let's quickly get our logout page working as well so let me pull up our projects URLs module here real quick so where we added the login and logout routes now for our logout view I also set a template name of users and logout dot HTML but actually let's remove that just for a second so that I can show you what it looks like without that set so

### look at the default logout [12:54]

let's just look at the default logout view so now let's open our browser and try to navigate to our logout route so I'll go back to our homepage here and we are currently logged in so I will go to forge slash logout so this is kind of weird so we can see that it says that we were logged out but it looks like the Django admin page so it says that we are logged out and then it gives us a link to log back in and if we click on that login again then it takes us back to the admin login now that's not what we want since we want an authentication system that works for everyone on the front end of the website and doesn't expose them to our admins section so all we need to do here is

### create a logout template in our users templates directory [13:36]

create a logout template in our users templates directory where we just created our login template and then tell our logout view to use that template just like we did with login so first let's tell the logout view that we want to use a different template just like we had set up before so I will paste that back in and so that will look for a logout template at users logout HTML so in our users templates directory right alongside our login and register templates let's create a new file and we'll call this logout dot HTML and now let's copy one of our other templates so that we have a starting point here so

### copy the registered html template [14:14]

I'm going to copy the registered HTML template and let's paste this into our logout template and now we're not gonna have any forms on this page so we can get rid of this loading krispy form tags here and we can also get rid of our entire form here and actually I'm just going to remove everything inside of our content block here except for this bottom div here that has our login link so I'm going to keep that but I'm going to get rid of this content section div so I will fix this tab tabbing here and now above our link I'm just going to simply put an h2 tag that says that we've been logged out so I'll put an h2 tag and then just say you have been logged out and then I'll just change our link text here for the login page and just say login again so I'll remove the text that says already have an account and then just make the login text here log in again so with this in place let's try to log in and log out of our website within the browser so let's pull up the browser here and go back to our homepage and now let's go to forge / login and let's log in with a user that exists on our site and now that we're logged in let's try to log out so now let's go to Forge slash logout and we can see that we have a message here that says you have been logged out log in again and really small change here it doesn't matter but I can tell that this has a little margin here to the left and that's because I left a class on there so you can see that our anchor tag here has a class of ml - let's just get rid of that because we no longer have any text to the left so save that and whoops save that and reload that logout page and our browser and now that's pushed against the left side there okay so we can see that now our site is using our logout page that we created in our templates instead of that default that had kind of the admin style so now it looks like the rest of our website so that's good and if we go to the admin page then that logout functionality should have still worked so it should tell me I need to log in and it does so that's good okay so now let's just go back to our home page okay so now that we have a registration page and our logins and log outs working let's change our navigation bar so that it changes based on whether someone is logged in or logged out because if someone isn't logged in yet then they should have a login link available somewhere on the page but if they're logged in then they should see a logout link instead of a login link so to do this we can open up our base template that contains the navigation and then put in a conditional that checks whether the user is logged in or locked out so I will go down and open up our project here and within our project our base template is within our blog app and that is in our blog templates and then blog subdirectory and then I'll open up the base template here now I'm going to scroll down until I see the navigation so the navigation is here from this opening knife tag to this closing nav tag okay so first of all here are our login and register routes right now currently our navigation links to the register and login pages don't actually go anywhere they're just these dead links and that's because those pages didn't exist when we created this base template and trying to use the URL tag for a route that doesn't exist will throw and air so now we can actually fill these in so I will put in a code block for each of these and we will say that we want this one to be the URL for the login and then we can copy that and paste this in and say that we want this one to be the URL for the register route okay so now we only want to see the login and register links if the user isn't logged in because if they are logged in then we know that they don't need to log in or create an account and Jango makes this easy for us by providing us with a user variable that contains the current user and it has an attribute called is authenticated that allows us to check if the user is currently logged in or not so here in our navigation bar we can

### put in a conditional [18:35]

just put in a conditional so right here is where our current login and register routes are located so I'm going to put that conditional right here open up a code block and I'm gonna say if user dot is underscore authenticated then if they are authenticated then it means that they are currently logged in and we will want to display the logout route which we don't have in our navigation yet but we'll add it in just a second so now we'll put in an else statement here and say else which means that they wouldn't be authenticated would be logged out and if they are not authenticated then we want to display the login and register routes here so we'll put that inside the else block and now we can simply end that if conditional by saying end if down here at the bottom and now all we need is a link for our logout route so I will copy the login route here and paste that and change this to the logout and change the route for that to be logout so one more time let's go through this we're saying if the user is authenticated then put a

### put a link to the logout page in the navigation [19:46]

link to the logout page in the navigation else/if which means if they are not authenticated and means that they're logged out then show links for the login page and a link for the register page in the navigation so now let's go to our website and try logging in and then see how this affects our navigation bar so all of this is saved so let's go back to our website and reload this so now let's see if our login link works up here so we can click on that and it takes us to our login page so now if we log in now if we look up here in the navigation now it's showing us a link to the logout route and that is because our user is authenticated so it shows that link instead of the other two and now if we click on logout now we've successfully logged out and now we can see the login and register routes up here in the navigation instead so it's always a good idea to give your users some visual feedback like that letting them know whether they're logged in or logged out because if they're logged in and they see a log in register route at the top then it's going to kind of confuse them and make them think that they're not currently logged in so this is a good way to do it okay so the last thing that we're going to be learning in this video

### put a restriction on certain routes [20:58]

is how to put a restriction on certain routes so that you can only go to those routes if you are currently logged in now you'll see this on certain sites all the time so say that I click on a link to edit my Twitter profile or something like that now if I'm not logged in then it'll first take me to the login page and say hey you have to log in first before you can view this page which is definitely a good thing because you just don't want anybody to be able to you know go in and edit our profiles so let's do something like that on our site so we'll create a route for the users profile that they can access after they've logged in so first let's create this route to their profile so I will open up our user routes so let's open back up our project let me close down some of the tabs that I have here since we've got a lot built up just get this cleaned up a bit okay so we want to

### create a page for a user's profile [21:47]

create a page for a user's profile so first let's create that view so that is going to be within our users views so I'm going to open up our users app directory here and then open up our views py from within there currently we just have our register view so we can just add this below our register view so down here at the bottom I'll say def and I'll call this profile and remember that we have to accept the request and right now we'll keep this extremely simple and just render a template that we haven't created yet so we will just say return render and we will render out remember that the first argument has to be the request and we will render out a template called users Forge slash profile dot HTML and we haven't created this yet but we will in just a second ok so now let's go ahead and create that template so within our users templates let's open these up so this is right alongside the log in log out and register templates will create a new

### create a new template in here called profile [22:47]

template in here called profile dot HTML and now as usual let's open up another template to grab as a starting point so I'm just going to grab the login template here and copy that and paste it into our profile template and now I'm just going to delete everything here in our content block and simply print out the current users user name so I will delete all of this and we will just print out the current users user name when they navigate to this page so we'll just put an h1 block here and then to access that user variable we can put in the double curly braces and then say user dot user name and remember that user is not something that we actually have to pass in to the context that is something that is built into Django that represents the current logged in user ok so now that we've got the view and the template created for this profile page let's create the route and our URL patterns that will use this view so to do this we'll just put this inside of our projects URLs dot pi alongside our registered login and logout routes and I'm just going to copy this register route here as a starting point and paste that underneath and now we can change this to profile so I'll say when we navigate to ford slash profile we want that to be handled by the user views profile view and we will name that profile ok so those changes should make that route accessible on our site so let's also add a link to this

### add a link to this page on the navigation bar [24:18]

page on the navigation bar if the user is logged in so I'm going to go back to our blogs based on HTML template where the navigation bar lives so that was within vlog templates and then based EML scroll down to our navigation bar again where we were checking if the user is authenticated and we want to display a link to their profile when they are logged in so we

### display this right above the logout link [24:44]

can display this right above the logout link so I will copy that and paste that in to the is authenticated section of this conditional and we want this to go to their profile so we'll say URL profile and we'll just say profile there now before we restrict this route to only be accessible to users who are logged in let's first make sure that this is working with all of our changes so far so let's save all of our files and all these are saved and now let's open this up in our browser and see how this looked so I will go to log in and

### log in with a user that exists [25:18]

log in with a user that exists and once we're logged in now we can see we have a profile and a logout link up here so if I click on profile then we can see it goes to a page that lists out our logged in users username so that is working so far but let me show you what the problem is here so if I log out then nothing is preventing me from going back and just manually going to that profile page so if I go up here into the URL bar and go to forward slash profile then we can see that we don't get anything on the screen and because it doesn't have a current user and doesn't know what user name to display so we want to put a check in place that makes a user login before they can access this page so let's do that now and this is extremely easy to do this we can just use a log in required decorator that Gengo provides for us so let's go back to our views our user views so within our users app I'm going to open up our views dot py and now we want to require that a user is logged in before they view this profile view here so to do this let's import the log-in required decorator so up here at the top we can say from Django dot country not auth dot decorators kind of long then we can import log-in underscore required and save that and now down here by our profile view we can simply add that decorator above our profile view so let me copy that and this is going to be a decorator so we'll say at login required now if you don't know what decorators are then it's not a big deal basically it adds functionality to an existing function and in this case it adds functionality to our profile view where the user must be logged in to view this page now I do want to mention that if you're using class-based views then the process of making the view require a login as a little bit different we haven't covered class-based views yet but we will in a future video but for now we can go back to our browser and try to reload that same profile page so now if I try to reload this while I'm not logged in then we can see that we get an error and it's telling us that the page it's looking for doesn't exist and it's looking for this page at forge slash accounts ford slash login and that's the default location that django looks for login routes but we decided to simply put our login route at ford slash login so we need to tell Django where it can find our login route and we can easily do

### adding a login url variable to the settings py [28:00]

that just by adding a login URL variable to the settings py file in our project so let's open our projects settings dot py file so within Django project settings dot py and we'll just go down here to the bottom and right at the bottom here right underneath this login redirect URL I will set one called login underscore URL set this equal to log in and log in is the name that we gave to our URL pattern for the login route so now if we go back to our browser and try to access our profile page then you can see that now we're redirected to our login route now there's one really nice thing that I want to show you here that's built into the Django login view now if you look at the URL then we were trying to access the profile page and it redirected us and told us that we had in first but if we look at the URL then we can see that there is a parameter in our URL that says next is equal to ford slash profile so it's keeping track of the page that we were trying to access and it will direct us to that page after the login and that's a feature that most people expect on web apps these days because remember our default redirect URL after we log in is the home page of the blog so imagine how annoying it would be if you clicked on a page and it told you that you needed to log in and after you logged in as since you somewhere completely different so this is a nice feature built in with the log in view so if I log in here then we should be redirected to that profile page since that is the page that we were trying to access so let me log in here so I'll log in with a user that I know exists and we can see that after we successfully logged in it sent us to the profile page so that will take us to the page specified in the next parameter if that parameter is in the URL but if it's not in the URL then it just redirects us back to the blog home page like we've seen before so now this profile page that we have here this is a route that is only accessible by people who have logged in and if they haven't logged in then it'll redirect them to the login page and force them to login first so this is working real nice okay so I think that is going to do it for this video hope that now you have a pretty good idea for how you can implement an authorization system in Django so we learned how to get the login and logout pages working and also learned how we could require a login in order to reach a certain route now in the next video we'll update this user profile page and make it so that our users can upload an image for their profile picture but if anyone has any questions about what we covered in this video then feel free to ask in the comment section below and I'll do my best to answer those and if you enjoy these tutorials and would like to support them then there are some ways you can do that these are sways to simply like the video and give it a thumbs up and also it's a huge help to share these videos with anyone who you think would find them useful and if you have the means you can contribute your patreon and there's a link to that page in the description section below be sure to subscribe for future videos and thank you all for watching you
