User Registration and Login Authentication | Django (3.0) Crash Course Tutorials (pt 14)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys so in this video we're gonna be building some custom user registration and a login page so a user can sign up and then log in and view pages but at this point all the pages can be viewed so later on in the video we'll actually set some permissions so a page can only be viewed if a user is logged in so that's what we'll cover in this video but in the next video we'll actually handle user permissions so for example we want an admin to see the admin dashboard but we don't want a customer to be able to see what the admin can see or do so a customer should be able to log in and only see what the customer is allowed so that's what we'll cover in the video after this one so it's kind of gonna be a two-part series so what I'll do right now is just go over our code and show you what we have because I did add a few things if you're following the course here so I just added a registration page so we have this view and a login page and I set up the URL paths and we have these two templates so they're in accounts and we have login dot HTML and registered HTML right here so they're just two blank templates so what I'm gonna do is actually start building in within these so make sure you have these built out if you're following along or you can just download the source code and then we'll go from there and actually start customizing these so let's drag our project in and let's make sure all the pages are working so we'll just check out forward slash login and let's check out register now so the paths should be working and the first page we're gonna work on is gonna be this register page so what we're gonna do here is we're going to import the default Django user creation form so Django actually gives us a form that handles a lot of that a lot of the functionality for this so it takes care of all the form fields for us things like password hashing and so on so we're gonna use that default form we could manually build us out but Django makes it very easy and I'll show you later how to customize this so we'll actually have some control over instead of just having to deal with whatever Django gives us so let's go ahead and run that import so up here let's do from Django dot contribs import user creation form and make sure these are capitalized the beginning of these and now that we have this form let's go ahead and just render it so let's do form it's gonna be equal to user creation form and pass that into our template and see what we get here so in our template I'm gonna build out a quick form will use register here so we'll just do form and I'll just set the method to post really quick before we forget this and the action is this it's just gonna be sent to that URL that we're currently on so we're just gonna leave that blank so we'll do that and now that we pass in the form we can render it so here is the default Django user creation form so if I do this and reload the page this is the default form that Django gives us so it gives us a username password and the password confirmation so what I'll do right now is actually create that input field so we can create a user handle that process and then we'll actually add an email to this form and we'll do a little customizing of this so or a customization with this so we can actually see how we can work with it and I'll show you how a user is added to the admin panel so let's go back to the template here and all we need to add is an input and the type will be submit and we'll just say create user and I just want to make our form look a little better so we'll just do as underscore P and what that's gonna do is just clean up our form so everything's not just kind of scrambled around here it's actually gonna put paragraph tags around each input field and make it show up line by line so at this point what I'm gonna do is go ahead and put a CSRF token here so when we submit the data Jango is actually able to handle this so CSRF underscore token and we need this for Django is just a safer way of sending data and let's actually process this form so we'll process it like any other form we've covered this in the past so if you're part of the series you should be familiar with this all we're gonna do is send the post data then in our view we're gonna say if request dot method is equal to post let's go ahead and throw that data into the forum so we're going to render the forum again and we'll just pass in that post data so the user name and those two passwords and then we'll validate that forum so we'll say if form dot is underscore valid go ahead and save this so if I save this form it's gonna create that user and this is the cool thing about using Django's default user creation form is that normally we would have to do things like make sure that user names not use before hash the password and so on so it actually handles all of that for us so it's as easy as saving it so what I'll do now is go ahead and move this to the side and open up the admin panel so we can see this user be created so I'll go ahead and refresh this and let's check out our admin panel and see this user be created so if I go to users we'll create our first user and we'll just call this user Eric IV and I'll give it a password and make sure to type it in twice there and submit so we'll not see anything that should have sent it yeah so it sent it but because I didn't redirect or anything like that we're still in the page but if we refresh the admin page there we go we have a user Eric IV so the user was created but I want to customize this form so I don't like how all of this shows I would like to handle this information myself and maybe put that onto in the template and I also want the user to have an email when the user is created and as you can see by the way here the password was hashed so that's what that formed it for us but I want to be able to later maybe do something like the first and last name the email and so on so for now I'll just add an email to this user creation form so let's go ahead and actually go into our forms dot py file so if you're not part of the series I keep my forms in a file called forms a py and we've already created some model forms earlier so we'll just go ahead and customize our user creation form from here so we'll just move it down here and let's run this import one more time here and I'll actually put that above right there and we actually need to import forms so from Jango import forms and we also need to import the default Django user model so to do this this is the user model by the way right here we're what you're seeing in the admin panel so django already created this for us so we just need to import this and start working with it so this is going to be from django dot contribs and then we need to do import user so it's a capital u that's the user model and now we can start working with it so it's actually very similar to this one right here so everything up until models is actually the same so now let's go ahead and create our form so let's do class and we'll call this create user form so I want to name it something a little different so this is user creation form we're gonna call this create user form so create user form is actually gonna inherit from this original form so it's actually gonna be a replica of the same exact form it's gonna have the same processing and everything so we'll just go ahead and replicate it and then customize the fields so we'll do meta we'll specify the model and this is why we needed to import that user so the model is going to be user and the fields instead of just giving it all the fields with this this method right here we're gonna do fields is gonna be and then we can actually list these out in a in a Python list here so I went in I went ahead and read the documentation so I already know what these are all called so just go ahead and either read that or follow along with me but we need the username and then we want to have the email present there and the two password fields are simply password one and password two and that's going to give us a form with only these fields right here so actually it's exactly what we have I here except for it's going to add that email field and let me refresh that I was working on this earlier so I want to make sure that everything is running so at this point you're actually going to see the form without that email that we originally had and then if I go ahead and rent this forum let's go ahead and import the user creation form so from forms I have order form in here and we'll just do that and import create user form so create user form is now going to replace user creation form so we'll go ahead and replace it there and there so now we're having a new form being rendered out into our template so if i refresh our template you're gonna see an email field appear here so we have the email field so now if i actually create a user and we open up the admin panel again so if i create a user and we'll just call this tim IV and this time we'll give Tim an email so we'll say Tim IV at gmail.com and I'll just go ahead and give them a password and I'm submitting again we're not working with that refresh but we should see if i refresh the admin panel we should see a new user appear so what's happening here is the same process is being taken care of but now Tim has an email field so again the password is still being hashed it's still that user creation form but that's how we're able to customize it so let's say I don't want these fields in here so what I'm gonna do is actually manually render this form so we'll go into our register to HTML file and I could do something like this where I can just go ahead and loop through all the fields so for filled in form and then I just can close this out with an end of four and then I can just say render each field so field and that would just go ahead and loop through my form and list out each field so it's not gonna have loops okay so it's not gonna have any of all of that markup there so I could also just use something like field labels so we can list out that label and access that attribute and now we have our cleaned up form so what I'm gonna do is instead of just looping through that and I just want to show you that method because that's actually how I handle a lot of my forms because this makes it a little bit more dynamic but I'm just gonna render each field so I'm gonna do a form dot user name and we can actually access each form feel this way so if I just do username it'll just be listed so we just have the username and I can just do something like username label so I can see which one it is a user named label and that should list that out okay so I'm gonna go ahead and just do this a few times so I'm gonna do this for email and just an email here and then I'm gonna do this for the two password fields so password one and we'll also do this for password two so I hope this makes sense I'm just simply accessing the attributes the form attributes and rendered in the mouse so if I go here we should see everything listed out here so that takes care of our form customization but now what we want to do is actually style this and what I did is actually went ahead and built out two templates for our register and our login form and I put them up on jsfiddle err so you can either download the source code from this project and follow along or if you want to actually handle this import as I'm doing it go ahead and you'll find a link the two links for the two forms in the description for these two jsfiddle accounts are here so we have our register form and it's just simply some CSS HTML and bootstrap and a little bit of JavaScript so you can actually go ahead and just copy all of this go all the way to the bottom copy that and in our template let's go ahead and move this down and we'll actually put this form into our tempo that we're pasting in so if I save this and refresh if i refresh this page we're gonna get this form right here so our real form is down at the bottom so what we want to do is make sure these fields are in here so we can actually process this so let's go ahead and take care of all of that so let's grab our CSRF token and see where our forum begins up here so our form starts right here the method is already post so let's go ahead and throw in our CSRF token and then replace all these input fields so I want to make sure that these are coming from my create register form or sorry create user forms let's go ahead and start with a username sol de forme that username there and then for the email let's replace that input and then then do formed email and let's go ahead and set the two password fields so password 1 and password 2 so I'll just copy that and throw that in here so I normally don't like doing this copying and pasting stuff but because this is a registration and login tutorial I don't want to have to cover all of this CSS so I figured pasting it copying and pasting wouldn't be too difficult here so let's go ahead and clear out this original form now so let's just delete everything up until that closing HTML tag so if i refresh this we should see our real Django form in here now and that's all removed and what's happening here is we're getting these placeholder values based on a little Java Script that I did you don't have to understand JavaScript just make sure this is paste it in but basically we grab all the form fields and access them but one by one because they are a list and then set the input values and I did this because I didn't want to go too far into customizing forms so just make sure that's in there and let's go ahead and build in our login page now so for login let's go ahead and go to our templates and do login dot HTML and now this one we're not gonna really need to customize from what we have in jsfiddle so if I go back we'll just grab this one right here and we can just copy pretty much everything and leave it as is so let's go to our login page now and that's our blank login page so in here let's just go ahead and paste everything so that's our login page I don't think we need any customization there but I already linked these up so this sign-up link so if a user doesn't have an account they can sign up and that's taken care of right here and I just threw in that URL path to the register page and then the register page also has a path to the login page already there so I built that in jsfiddle so as long as your URLs are called that you should be fine so if I decide I want to sign up I can go to this page if I want to log in I can go back and forth so now let's actually go ahead and handle another user signing up but this time redirect them to the login page so that user can log in and also send out a flash message so when a user is created we get alerted for this so to redirect a user all we need to do is use this redirect import that we already added so we've used this before in the tutorial series but if you're not part of that go ahead and just import that from Django shortcuts and let's just to return redirect and then whatever we call their long login page so we want to send the user to the login page once they register we don't want to automatically log them in at this point so we'll just go ahead and pass that in so really quick before we actually start working with the flash flash messages I want to show the heirs when a user signs up so if I go to sign up and we add in some information let's just say Dennis 3 and we'll just give some kind of email and if I type it a password here so I'll just randomly throw my password and the next password doesn't match so it doesn't match my characters in by length I want to see heirs show up if I register in and something doesn't look right so at this point I'm confused I don't want to see I don't see what's going on here so if i refresh this and throw in the error messages so to do that just above this link right here I want to throw away in my form err so if I just do form dot errors and again that's just above the area where we can link up to that login page if I throw in the form airs any air that we have in our form so if I just type in some random stuff here in hit register let's actually make this in a some kind of gmail account and hit register so password - so the two passwords don't match the fuels are not active so now my errors are actually showing up so let's go ahead and actually send a flash message and redirect to the login page so at this point our redirect is handled so on forum save we redirect to the login page so let's go ahead and import that flash message so what a flash message is is basically a way to send a one-time message to the templates so I pulled up the documentation here and I'll actually link this in the video description but we have a few types of flash messages we can actually use here so I'm gonna go ahead and copy this so I want to type that out and we have messages for information success warning and so on and we can actually write in our own statement so what happens is after that registration is complete we're gonna temporarily hold a flash message that will render out in our login page so we'll say person a has been successfully created and added to the database so what I'll do here is and this will make much more sense once I just start adding it so we imported from Django Duncan trip in port messages and now what we need to do is actually go ahead and add that message to our template here so we don't actually have to pass it into our template but once we state it it's gonna temporarily be held as a value so we're gonna do messages and we're getting this from this import and we're gonna do a success message so after that form was successfully submitted we're gonna throw in the request and again it's all in the documentation so I'm just using this one we're gonna pass in this request right here so we're gonna do a request and then we're gonna say our message so we're gonna say account was created for and we want to throw in that username so we're gonna add a space there and we're gonna concatenate the username so to get the username we're gonna say user and we're just gonna grab this from the form so it's gonna be equal to form dot cleaned underscore data I don't look over my notes here and we're gonna get and then the username so this just allows us to get just get that username without getting any other form attributes or anything like that so we'll just throw in the username and at this point we have our flash message that gets sent we redirect to the login page so let's create a real user now so at this point let's go ahead and go to our login page or our register page and let's go back to our signup page and we'll just say Dennis 3 and we'll do Dennis 3 at Gmail and I'll go ahead and just throw in a password so and this person is not actually gonna get email that's not my email but I'm not actually having a confirmation being sent right now so we'll just do register so what happened here is that flash message didn't actually show up but what happened here is that user was just created and that flash message was actually sent to this template and we just got redirected so I'll actually sign up one more user and I forgot one thing here in order to render out the flash messages we'll go to the login page and again just above this area is where we want to throw in our flash message so well actually we can actually access the messages in templates by just doing something like this so we'll just do four message in messages and we'll just end that loop and again we didn't have to actually pass it in it's just stored as a value that's what jingo takes care of for us and we'll actually throw in the messages into this paragraph tag so we'll just do message so for every message for every message that we have we'll just be thrown in here so we'll just give us an ID and I actually have this styled up in the template so we'll just do messages and now if I sign up another user and I'll say Dennis 4 and we'll do Dennis 4 at gmail.com and we'll give it a password and we should see that flash message actually appear now so there we go account was created for Dennis 3 and Dennis 4 so apparently they just stored that message probably because we didn't refresh but that message should appear once and then once i refresh that login page it'll disappear and it'll only be there as a one-time value so let's actually go ahead and handle the actual login authentication so let's go ahead and login Dennis four and then restrict some pages so we'll go to our views and run a few imports here so let's go ahead and do from Django dot contribu in ports here so we'll import authenticate and this will just authenticate a user for us and then we'll do login so this will actually login a user for us and then log out and we'll work with these all in a second here so let's go down to our login view and actually process this so our login form sends our username and password ans post data so the first thing we're gonna do is check if it's a post method so if request dot method is equal to post let's grab the username and password so we're gonna do request dot post dot get and we'll do username and we'll just do the same for password so we're gonna grab the values of these fields and if I go to my login dot HTML page we're getting these from these two inputs so the first import the first input the name is password and this one is username so we're gonna grab these two but before we actually process that let's adding a CSRF token so CSRF underscore token and that's just to secure the data it won't let us submit it without it and once we get the username and password let's go ahead and authenticate this user so let's make sure this user is actually in our database so we're gonna use this authenticate method here so if I go down here we're gonna first set the user value to user and then the authenticate method and this method is gonna take in the request and then the user name so the user name is gonna be equal to username and then the password is gonna be password so let's go ahead and throw these two values in and I actually need to set these and this one needs to be password so the password is going to be whatever we pull out of that form okay so we have our user name and password and we authenticated it so once we authenticate it we first want to check if that user is actually there before we redirect him so if user is not none so if we actually we're able to authenticate and see that there is a user let's go ahead and log this user in so the login method and there's a specific reason to why I call this login page if we call this login we're actually gonna have a conflict because that's a Django method here so we're taking this login method right here and we're gonna throw in the request and then the user so we're gonna log this specific user in and then we're gonna redirect them into the home page so we called our dashboard here home in the name so we're gonna go ahead and just throw that in and we should be redirected so let's go ahead and actually a log a user in so if I go back to my login page so let's go to login Dennis for if I go ahead and hit that string value object has no attribute pk so let's see what's going on here give me a second to just debug this and it looks like I threw in the username and not the user so let's go ahead and just fix that really quick I actually need to throw in the validated user so if I go ahead and log this user in again that should redirect me and I think I need to return not just redirect so return redirect sorry about those mistakes there will refresh that one more time and there we go so we're now in the home page so what I want to do is actually provide a logout method and then go ahead and just restrict some pages so right now if the user is logged out we'll still be able to access this page so let's actually add a little bit more function out of here so what we want to do is actually first check if the user is not none so let's say we input the information wrong here so we'll say else and what we want to do is actually send in a flash message so we want to say messages and that's gonna be the info message and we'll throw them the request and we'll just say you use our name username or password is incorrect so what's happening here is username or password is incorrect so what's happening here is because we're looping through all of our messages all the messages that get sent here will be output so we'll throw in that message and then we want to return this same page here so we'll just go ahead and make sure we send the user back to the login page so let's go ahead and refresh that really quick and let's just say we'll throw in a user that we know we don't have so if I hit login context reference before assignment and I actually don't think I need to return that template so let's try that one more time so if I just go ahead and do this and hit login okay username or password is incorrect so perfect so we have that air-handling so we throw in the message and we render that user back to the template so and if it is a correct one then we log them in so let's go ahead and add a logout method display the user name so we know which user is actually logged in and then go ahead and restrict some pages so to throw in that login or that logout method let's go ahead and create a view here called logout so logout user and we'll put on the request and what we're gonna do is just go ahead and send the user back to the login page so a return value is gonna be redirect and we'll send them back to the login page when a user logs out so we want them prep to login so let's go ahead and throw that in here and we don't need to build a template for this and we'll just do logout and we'll throw that in here and then we'll just say logout user for the view now before I forget this part we actually need to process the logout method so in that logout view we're gonna use this logout method that we imported and just log the user out and then redirect them to the home page so all we're gonna do is just throw in the request and that should handle logging the user out so if I go back to my navbar we'll actually go ahead and just add the link up here so we'll go ahead and make sure everything's refreshed let's go ahead and minimize this because my screen is cutting this off will actually put the logout button and the name of the user right here so the first one we're gonna do is gonna be just a span tag and we'll just say hello and then the user name and then we'll also throw in a link for the logout method so we'll put that into a span tag so it's aligned and we'll just do H ref and close this out and we'll say logout and the URL is just going to be that new logout URL that we created so URL and logout it all style this in a second but now when we go back to our template we're going to click on this link it's gonna send us back to this method or this view and then send us to the login page so if i refresh this we're gonna see the hello message and logout so if I hit logout we're gonna be sent back here and then if I log in will be logged back in so let's go ahead and actually display the user name so you can display a user name by simply accessing request dot user right in the template so you don't need to pass that in and we should be able to see a user name so if we're logged in as Dennis and that says Dennis right there so I'll just go ahead and style this so we'll just say hello - msg so hello message and we'll just add a little bit of styling right here make that white so we can actually see it so just put that in here and we'll reference the ID so hello - message and font size we'll just make sure that's a little bit bigger so font size is going to be 18 pixels color is gonna be white so we're gonna use this hex and that's gonna be pound sign ffff that should give us white and we'll just set margin so we'll create some spacing so we can actually see it so margin - right is gonna be 20 pixels so let's actually turn this into a class and we'll just say we'll just do this to bold so the logout method has a T now I know the naming doesn't actually really match it but that's okay for now and we'll throw that to the link so that'll be a little bit more styled so if i refresh this there we go so hello Dennis lock out and let's log in as Dennis - and the password should be the same and there we go it's Dennis - so if I actually log out and view this page we're able to see it because we're not restricting it so at this point it just gives us an anonymous user so let's go ahead and actually restrict the user access so we can only see these pages when we're logged in and then if we're logged in and we're on the home page we don't want a logged in user to be able to see this we want them to be able to read we want them to be redirected back to the home page so it'll send them there so we'll restrict the login and the register page and when a user is logged in so this process is gonna be a little bit manual right now normally once a project is bigger you want to build in middleware for something like this - where this can all be processed within one file but at this point what we're gonna do is actually put in something called login decorators above all of our views that we want restricted so let's go ahead and run some imports first and I'll explain what they do as we go so from and then let me just see what those were called here so from Django dot contributors make sure I spelled that right import login required so login underscore required and oops so the login required decorator so what we're going to do now is we have to put this decorator above every view that we want restricted so the first page we want restricted is going to be our home page so we're gonna set that decorator above the view and then what we're gonna do here is we're gonna say if that user is not logged in go ahead and set the login URL and send them back to this page so we want to send them back to the login page so login required and that needs to be an @ symbol and we'll just put this above every single view that we want restricted so I'll first put that above the home page and let's go to our home view so as I go to that home view you can see in the browser that I'm actually being redirected so if I log in I'm allowed to be here once I log out and I try to go back to that URL I automatically get logged back out so or I get redirected so if I go to the products page I'm fine so what I need to do is make sure that that decorator is being put above every single view that I want restricted so I don't want anybody creating orders if they're not logged and I don't want them updating anything and remember that login URL so where are they being redirected if that user is not logged in so I set that above everything and that should now restrain all the pages so what I want to do now is go ahead and manually write some functionality that restricts a user from the login page so if I go to the login page right here or even the register page actually if I go here I don't want a logged in user to be able to go to the login page or the register page so I don't want them people to see this if they're here they need to be redirected so what I'm gonna do is within my register page I'll start here I'll say if request and remember I'm able to just access the user this way so I'm accessing this request right here so if request that user is authenticated so what we're going to do is say is underscore authenticated and that's just a method on the user or sorry not a method but a property so you would do something like that you just do is authenticated as is go ahead and log the user in but if they're not or if the user is authenticated sorry so if they're authenticated go ahead and redirect them to the home page so return and again middleware will let us write this functionality better and I might do a video on that in the near future but for now we'll just manually do this so you can understand what's going on will redirect the user to the home page if they're authenticated and if not so else and then I'm just gonna indent this and we'll just say log that user in so we'll actually indent everything and we'll do the same for the login page so we'll just go ahead and again this is a really bad way of doing this because you're gonna have to do this for every single page as far as putting the decorators on and writing this kind of logic but I'm doing this just to understand what's going on but we will fix this up later so redirect the user to the home page and then else run all of this functionality right here so let's go ahead and give this a try so if I am on the login page the user is currently logged in user hasn't actually be authenticated so it looks like I misspelled something so I'm just gonna go ahead and fix that and we'll fix this one above right here okay so if I try to go to the login page I get redirected here if I log out and I try going to the home page so now I can actually access the register page but if I try going to the home page I'm logged out so that's all we have for user registration and logging in in the next video we'll actually handle user permissions so different types of users can access different types of data and pages so make sure you're watching and make sure you're subscribed and thank you for your support
Info
Channel: Dennis Ivy
Views: 525,935
Rating: 4.931757 out of 5
Keywords: Programming, Software Developer, Dennis Ivy, Dennis Ivanov, Django, Python, Authentication, Login, User Signup, Registration, Restricted pages
Id: tUqUdu0Sjyc
Channel Id: undefined
Length: 37min 43sec (2263 seconds)
Published: Fri Jan 03 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.