Python Django Authentication System with Password Reset; Complete Project Beginner Friendly Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi guys in this video we're going to use Jango to create an authentication system where users can register log in log out do whatever they want and forget their password because we'll be creating a password reset system the one where users receive an email with a tokenized URL that expires after a period of time all right now let's start coding let's create a new directory let's call it oath is very easy and and now we want to open it in Visual Studio code I'm just going to right click and open in terminal and then I'll type in code space period and hit enter next up I'll open Terminal because I need to make sure that I have python installed we can check by typing in pi or python D- version and hitting enter this is the version of python I have installed if you don't have python installed please make sure to install it you can go to to python.org downloads download it and install it very easily if you have python installed then it's time to create a python environment to do that just click on view command pallet python create environment we will select venv to create a virtual environment and then we're going to click on our Python's path and wait a bit until creating environment finish next up I'm going to open a new terminal just to make sure that it recognizes the virtual environment now we're going to need to install Jango to do that we will type in PIP install Jingo and hit enter then we're going to have to wait a bit while we wait I would like to ask you to hit the like button if you're enjoying the video and to subscribe if you haven't ready thank you and now that we have Jango installed we can create a new D Jango project the command for starting project is Jango admin start project and then the name of our project so let's type that in and hit enter all right we have the scaffolding of our project set up for us and what we'll do next is CD into our project directory which is my site hit enter we'll use manage.py to run server so Pi manage.py run server all right if we click and follow link we'll see that the install worked successfully and everything is great let me show you something I love about Jango which is the admin page which we get to by adding slash admin to our URL and hitting enter and as you can see there is a login page to be able to login we're going to have to create super user to do this let's go back to our ID e and we first need to disconnect by hitting controll and C or command and C then we're going to need to run migrations as you see Jango is telling us that we have 18 unapplied migrations so Pi manage.py migrate and we hit enter and now we can create super user so Pi manage.py again and this time we'll write the command create super user after that we'll get prompts asking us for a username email and password and confirm password if our passwords don't match we'll be asked to type them in again now we need to run server again so P manage.py run server now let's follow link and go back to the admin page and let's type in our username and our password and hit enter and voila we have logged in into the user Administration page and what we can do here is create users and groups for our users we should also see all all the users that are available and we can do so so so much more with our admin page it's actually awesome all right what I want to show you now is how easy it is to create an awesome authentication system and make it look really good super duper quickly let's go to our urls.py over here we have a very handy explanation from the awesome Dango team let's just delete it and as you can see over here we have the path to admin that we have visited earlier now we need to tell Jango that we also want to create path for authentication by the way Jango comes with authentication installed and enabled complete with middleware and everything so let's go back to our urls.py and we're going to add another path to our URL path patterns and that's going to be path accounts and now we're going to need to import include from Jango do URLs because we are going to need to include Jango doc cont trip. oath. URLs and if we run server again we'll find that the URL pattern accounts was created for us if we go to it by typing in slash account accounts slash we will find that Jango created all of these URLs for us which really does save us a lot of time now I would like to show you how we can create custom templates for each of these URLs what we're going to need to do is first go to our settings.py and import OS we are going to need it in order to J go where to look for templates so we're going to go here where templates is defined and in dares we are going to add os. path. join base D templates and now we can create a templates directory in our base directory which is here on the same level as manage.py and Jango will be able to find it so let's do it let's create a directory call it templates and Jango will look for the templates related to authentication within a directory inside the templates directory that's called registration so let's create it and let's create within it a login. HTML file however before we start typing code within our Authentication template files let's make our life much easier by creating a base. HTML file in it we can add our HTML boiler plate and this way we are not going to have to write it in every page we create I'm just going to get some boiler plate from anywhere online just copy and paste and then I'll clean it up another thing we can can do with our base. HTML is create blocks for example we could go here where we usually have our title and we could create a block to define a block you just use curly brackets and between the curly brackets you put two percentage signs and you write the word block and then you write the name of the block you can call your blocks whatever you want but since this block is where we'll be keeping the title so we'll call it block title and then you have to end block where you want to end it so just end block we can also provide a default title that we can override if we choose let's make the title my site and if we want to override it later in any template that will inherit from this base we'll be able to do it very easily now let's go to our body element and create a block and call it content and that's where our content will be of course we could create as many blocks as as we want for now let's just keep it minimal and let's go back to our login. HTML to use this Bas template what we're going to need to do is use the word extends and type in the name of the layout template or the base template and now let's get hold of block title and let's make the title here login because this is the login page we have to remember to write and block for the main part we'll open block content and let's also write and blog so we don't forget it and now for the cool part we're going to create a form element with the method post and action URL login and within our form we want to add csrf token csrf stands for cross site request forgery and that's a security measure that helps protect against certain types of attacks and the fact that he can just add the csrf token that easily is also one of the things I really love about Jango then to render our form form. ASP and then we want to create a button give it the type submit and we want it to say log in now let's run server again so Pi manage.py run server and go to account SL login and here is our login page if we try to log in using the super user we've created earlier it should let us so let's try and it actually worked we are logged in however upon logging in by default Jango redirects users to accounts SL profile and since we haven't defined a URL pattern matching accounts SL profile we're getting a 404 error anyhow I have promised you a beautiful authentication system so let's get to it when using Jango static files are what we refer to when we mean files such as images JavaScript or css let's go back to our project let's create a new directory and let's call it static and inside it let's create a new directory and call it CSS that's where we're going to have our CSS file and while we're at it let's create a new file and call it styles. CSS before we'll be able to actually use this files we're going to have to tell Jango where to find it so we're going to go to our settings.py and under Bas there we are going to type in in all caps static files underscore dares and then we're going to open a list to point to the location of our static directory so os. pa. join and then in O cap space there comma static now we should be able to use our static folder and apply CSS styling to our templates let's go to our base. HTML and in order to be able to use static files we're going to need to add in this line of code on top which is load static then we're going to add the link tag to our head element like we do with any HTML file but there's a difference in the href because we are going to link to our CSS using D Jango templating language so we'll start with the curly brackets then the percentage sign and between them you'll write static between single codes We'll add in the relative path to our files so CSS styles. CSS let's go to our styles.css file let's start at the body element and we can add a background linear gradient let's set it to to bottom and let's make the color transparent to let's say blue let's refresh oh this is not what I had in mind okay so let's target our HTML element and let's set height to 100% to fix this and refresh how about we change font family to S sarif while we're at it right now how about we try and Center our form by changing the body's display to flex and adding align items Center and just ay Conant Center let's refresh and let's give the body height 100 VH yes cool and now let's add some styling to our form element let's give it the background color white let's make its border radius 5% padding let's say to Ram font weight let's say 700 and let's give it some box Shadow 0 0 10 pixels and rgp a0 Z 0 0.3 Max width let's say fit content to Center the form horizontally let's add margin zero oo and now we want to Target form input as well as form select form text area and you want to make their width 100% margin bottom let's say 10 pixels padding also 10 pixels box sizing order box and let's also add in some box Shadow for a good measure and make border none and maybe add in some padding let's make it 1 M let's refresh now let's target the button so form button display let's make it block withd 100% padding let's say 15 pixels font size let's say 16 pixels let's refresh and now let's choose a background color let's make it something bluish right and Border non color white border radius say 5 pixels and let's make the cursor pointer all right let's refresh how about we also change the background color on Hover so form button hover let's make the background color let's copy this color and then make it slightly darker we can add the transition effect so so transition background color and let's say 0.3 seconds is in let's refresh and I think it looks really really good however I'm not sure if the shadow is showing maybe I made a typo so let's fix that I think I added this comma by accident let remove the commas all right and I think that looks better let's make this five pixels all right now let's see what happens if we write a username that doesn't exist and try to log in oh we get an error and it completely ruins our design because we set the max width to fit content all right so let's change that by setting a width for our form I'm going to set the width to 300 pixels and refresh yeah and this looks better how about we also add styling to the error and make it look a little bit less ugly so to Target it there will be form error list Li and let's set the list style Type To None and let's change the color Also let's make it some reddish color since it's an error but since our color palette is blue let's try to make it a bit on the cooler side maybe like this yeah I guess that looks better let's also add um media query just to make it a little responsive so add media screen all right let's make it Max with 600 100 pixels form width 90% all right and now let's see how it would look like on a phone I think it actually looks pretty decent now I want to show you how easy and painless it's going to be to create the rest of the views for our full-fledged authentication system let's create the view for password reset we should name it password reset form HTML I'm just going to copy everything from our login. HTML file and paste it and I'm going to delete this part the action and I'm also going to change the page title and the blog title and make it password reset and now if we navigate to accounts slash password reset here it is here's our form made for us or already let's change login to send password reset email and here it is now let's try hitting it and Jango knows we haven't inserted a valid email all right so if the user inserts a valid email and hits this button the user is supposed to receive an email with a tokenized link that would take him to a page that would allow him to change his password let's actually register an email that Jango is going to use to communicate with our users first the first thing we want to do is create new file and call it EnV that's where we're going to keep sensitive information like our email and email password so let's create two variables the first one would be the email that we're going to use the second one would be the mail password I'm going to write a fake email just to show you an example and a fake password and then I'm going to change them so let's say my fake email is fake mail.com and my password is fake password six of course those are fake and now in order to be able to use our EnV file we are going to need to install a python Library called do EnV and I'll just copy the command pip install python. EnV and disconnect server paste it and hit enter all right and once it's installed let's go to our settings.py and then we want to import load. EnV so from do NV import load. n then we want to load. NV and let's scroll all the way down and let's declare a variable and call it mail because we want to get our email address so os. Environ doget mail and then we also want to get the mail password so same thing os. Environ doget and then mail pass and then we're going to declare another variable call it email backend and it would be Jango doc. mail. backend. SMTP email backend and then here we're declaring another variable and it's email host and since the email I'm using is an Outlook I'll type in SMTP May . outlook.com and then email Port is 587 email use TLS true email host user is mail this variable and email host password is mail pass and then default from email let's make it also mail and can add in email subject prefix let's make it password recovery and now how about we create the file that will actually contain the email that will sent to our users when they request a password reset all right so the file should be called old password uncore reset uncore email. HTML so let's create a new file and give it that name and I'm going to go back to the D Jango dos and I'm going to copy the email body template provided and paste it if we examine it we'll see it says someone asked for password reset for email and here we have an alias for the actual email of the user and then follow the link below and protocol is like HTTP and then the domain of our website and then it links to password reset confirm here we have the user ID and here we have a generated token all right so let's create the template View for the password reset confirm so new file and we're going to call it password underscore reset underscore confirm firm. HTML and just like we've done in our other HTML files related to our authentication views let's extend uh base. HT actually I'm just going to copy the whole thing and then edit it all right so let's change the title to password change confirm and let's delete this and inside our block content we also have a form with the method post and it will also contain a csrf token and then we would want to render our form ASP and also add in a button with a type submit another file we should also create is is password reset done. HTML and for this one just want to tell our user that we've emailed them the instructions so we've emailed you the instructions for resetting your password and now the one thing left to do other than creating a user and seeing if they can can change their password is adding a reset password link to our login page so let's do that so under the login button I'm just going to add a link element and make the hrf URL password underscore reset and make it say lost password and that's it all right let's check on our website let's go to account slash login and here is the lost password link that we can click on all right now before we try out our authentication system and see if the email gets sent let's go back to accounts to check um if we've created a template for each URL path and I think the one that's missing is password reset complete which is supposed to show up after a user successfully changes their password so let's create it quickly password reset complete. HTML so um just like we've done with the others let's let's just copy this and she'll just say password changed all right I think now we're ready to create a user and then test the authentication system on them so let's go to admin and add user and let's make the username PCO let's give it a password save and then let's input a real email address and save right we have a user with an email address now let's go back to accounts SL login and let's click on lost password and let's input an email associated with an account we've created and let's hit send password reset email okay and now we see this page which is password reset done all right now if we check our email we should find that we've received an email hopefully so let's check I'm guessing that it's going to be in the spam folder and here it is that's our email okay let's click on the link all right and here is our password change form okay let's input a new password right let's save it yay password changed cool now the only thing missing from a full-fledged authentication system at least in my opinion is a registration form so let's go back to our project and let's create a new file within our project directory and let's call it views.py all right and now we're going to import a bunch of things the first of which is our user model so from D Jango do contra trib do oath. models import user and then we want to import user creation form so from Jango do cont tr. oath. forms import user creation form and then we also want to import login so from jro Contra do oath import log in and then we also want to import forms from Jango so let's do this right and now we're going to Define class let's say registration form which will inherit from jango's user creation form however unlike the typical user creation form our form will have an added email field so forms. email field and we want to make it required and then let's add Class Matter and our model is user and the fields in our form will be usern name email password and password too now let's define a view that is going to both display our register ation form and process the form when submitted def registration underscore View and it takes in the Pam request and then if request. method is post then form is going to be registration form request. poost and then we want to check if our form is valid and if it is then we want to create the user so form Dove and then we want to log in the user so login request user and then we want to take the user somewhere but the problem is we haven't created an index page yet so I'm just going to return redirect index and then we can create an index page also we're going to need to import redirect so from Jango shortcuts I'm going to import redirect and we're going to need render as well to render our HTML files okay and then if the method is not post then form is registration form do we want to return render request and registration SL register. HTML which is an HTML file we have not created yet and we want to pass in our form now we have two things on our to-dos or actually three we need to create the index view so let's quickly Define it so def index request and then we want to return render request and index.html now we're going to have to go to our urls.py and create the paths to our registration View and our index view then we're going to have to create the templates for both of them so let's let's go to our urls.py first first we have to import our views so from views import index and registration View and then let's add in path to index so index the name index and now we want to add in the path to our registration view as well so it will be path and that's make a accounts slash register registration View and the name is register okay and now let's go to our templates and let's create a file and call it index.html and what I want to do is I just want to First extend base. HTML and then just copy these lines of code from the docs um if user is authenticated then our page would say welcome and show the username thanks for logging in else to say welcome new user please log in let's link to our login page and our register page which we still need to create the template for to register we forgot to add block content and and block all right now that we have them let's check it out let's go to slash index and here it is it knows me it says welcome super Pico thanks for logging in if we want we could also add an option for logging out log out views in Jango expect a post request then it would be best if we create a form element with the action URL logout and the method post right let's add in a csrf token as well and I'll create a button with the type submit and it will be our log out button before we preview what we've just done I think it would be much better if we go back to to our urls.py and change the fact that we have to type /index in order to get to our index page and make it take us to our index by default so to do this we just leave empty quotes like this and now let's go to our website and see if it works oh let's go to our index page again and let's remove this and put it inside of our form all right so that's what happens when we are logged in if we click on log out we will be redirected to jango's logout template that we could have overridden if we wanted to just like we've done the other authentication templates however we could also do something cooler which is just go to settings.py and make it redirect us back to our index page because I I think we don't need a log out View at all so to do this add in the line logout redirect underscore URL and between quotation we'll just add a slash Also let's do the same thing for login I'm just going to copy this line paste it and instead of log out we'll have log in all right and we need to uh run server again all right and let's refresh okay let's log in right if we click on log out we would log out if we want we could commit some um CSS crimes and just add a form element just so that we have homogeneous design it looks like this of course if you're developing a real website make a div you know all right and now let's just create our register. HTML files so register. HTML okay and just like we've done so many times before let's let's just copy the login form and paste it and here we'll change the title to register and let's change the action to URL register okay we'll keep our csrf token as this forms P let's change the button content to register and here let's add URL login and it can say already have an account all right I think that is it this should do it so let's go back to our page let's refresh and let's hit register oh I made the typo really really silly typo uhoh there is an extra password field and I think I know why that is right so let's go back to our ID and find the views.py I think that the reason we have an extra field is because I have named password Here incorrectly and it should be password one because we're extending user creation form model and typically the first password is named password one not just password so hopefully now if we refresh our registration form would be fixed yay it is fixed we have only one password well we have two password Fields just like we're supposed to all right so let's try registering let's try making a new user let's call it test user and let's input an email let's say test at tester. test and and let's add a password confirm it and then register yay it worked and we see welcome test user thanks for logging in all right you guys looks like we've done it let's try to log out and now it tells us welcome new user please log in or register and we can choose to log in or register all right you guys we've done it yay all right guys thank you so much for watching I really had so much much fun coding with you I hope you've enjoyed this video if you have enjoyed it please hit the thumbs up button and if you haven't already please subscribe oh and if you have any questions any suggestions ideas anything at all leave that down in the comments i' would love to read that thank you so much have a lovely day and see you next time bye-bye
Info
Channel: Piko Can Fly
Views: 7,447
Rating: undefined out of 5
Keywords: python, django, fullstack, webdev, javascript, backend, developer, project, beginner, friendly, coding adventure, fireship, code with, code along, tutorial, guide, awesome, smart, best, cute, coding, girl, coders, girls can code, programming, API, portfolio project, easy, idea, portfolio, develop, code, js, html, django templating, full-stack, design, admin, database, authentication, user class, admin class, .models, superuser, django project, settings.py, register, templates, webdev explained, login page
Id: hNOrcz2y4c4
Channel Id: undefined
Length: 41min 21sec (2481 seconds)
Published: Sun Jan 21 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.