Build a User Authentication Web App With Python and Django

An Essential guide for building User Authentication web apps with Django

Chowa Cross
Towards Data Science

--

Photo by Faisal M on Unsplash

User authentication is an integral part of most applications and in general can be seen as the process that which allows device to verify the identify of someone who connects to a network resource. In our case, these refers to our web app. Nowadays they are many technologies and web frameworks that make this task easy but in our case, we shall concentrate on the Django web framework to perform this task.

Django by default comes with a user authentication system. It handles user accounts, groups, permissions and cookie-based user sessions. For this tutorial we will be using mainly class base views(CBV) because they are a lot more easy to understand, save time and already have test built into them as compared to the functional base views(FBV) which are a lot more easy to customize but do not have test built into them.

In order to better understand and appreciate this tutorial, a basic understanding of python and the django framework is essential.

Requirements

All of the above with the exception of Bootstrap 4 can be installed directly from the requirements.txt file by running the following code on the command line pip install requirements.txt

N.B: The requirements.txt file is found on this projects github repo. The link will be given below. With regards to bootstrap 4,you can get the CDN from the official bootstrap website

Project Setup

There is no rule of thump when it comes to setting up your Django project but they are certain guidelines which developers are advised to follow. With that being said, my personal preference with regards to this can be found on my github repo.

We begin by creating our working directory and then create a virtual environment where we will install the project requirements.

Creating a virtual environment

conda create -n nameofvirtualenvironment

then, we activate our virtual environment with

activate nameofvirtualenvironemnt

Next

create a requirements.txt file in working directory and then copy and paste the contents of the same file from this project github repo,then run the following on the command line;

pip install requirements.txt

We mentioned in the very beginning, a basic understanding of Django was a prerequisite as such it’s assumed the readers already posses a basic know-how on to how setup their templates and static files.

Lets begin by creating a Django project called src by running the following command,

django-admin startproject src

Next we move into our “src” directory and create our first app called authapp by running,

python manage.py startapp authapp

In our authapp,we create a file called urls.py followed by an template folder, then an authapp folder.

We begin by setting up our urls.py file in our created app where we shall map the urls to their appropriate views.

For convenience purposes rather than writing each url individually through out the article I thought i wise to begin by writing all at once.

N.B: We are using the built in CBV from django.contrib.auth.views which have all already been built into the django framework by default.

The above file showcases all the urls we shall use for the project. Furthermore it can be clearly seen we he have mainly used class based views(CBV) but for our edit, register and dashboard views which are functional based views(FBV) and will be explained later. Each of the CBV can be seen to handle a single aspect when it comes to handling user registration with each being linked to its appropriate html template with the template_name() attribute.

N.B: reverse_lazy is used for resolving Django URL names into URL paths

In our authapp we create a forms.py as seen below which will be responsible for createing,handling and customizing the forms in our app. We will create two classes here that is the UserRegistration and UserEditForm with both inheriting methods from forms.ModelForm. Both forms will use as their model the default User model which contains attributes such as email, password, first_name, last_name etc. The actions we will perform on both forms can also be easily done using the UserCreationForm and UserChangeForm which are both built into Django and can be accessed using,

from django.contrib.auth.forms import (UserCreationForm, UserChangeForm)

Our earlier intention with the forms.py file was creating,handline and customization of forms as such for our UserRegistration class we intend to include a password and confirm password field into this form in correspondance with our User model attributes, which can be seen above. Furthermore both classes have their appropriate models and fields contained in that given class. In the UserRegistration class, we do have a custom validator method shown with the clean_password2 which simply ensures both passwords match else it raises a validation error.

As a role of thump, custom validator methods in Django begin with a

def clean() or def clean_fieldname() method as seen above.

lets move over to our authapp views.py file

After doing all the necessary imports, it can be seen this file has three main functions.

  1. def dashboard(): This function contains a login decorator making it only accessible when the user is logged in which then renders the “Welcome to your dashboard” text to the user.
  2. def register(): This function is responsible for registering a new user to our application and uses the UserRegistration class we created in our forms.py above as such if the form is valid, a new user is being created but the said user is not being saved directly into the database hence form.save(commit=False) because we need to modify the data before saving it into the database. We then move forward to hash the new user password using new_user.set_password() for security purposes .After this is done,we then save the new user to the database with new_user.save(). Else we return the UserRegistration form.
  3. def edit(): This function contains a login required decorator. The UserEditForm in this function, gives the user the ability to edit the fields contained in the UserEditform class we setup in our forms.py file and if the form is valid, its being saved in the database, else the UserEditForm will be returned.

Both the edit and register functions in our app, deal with a POST requests implying they both have the ability to create data.

Creating a User profile

In order to create a user profile for each of our registered users in our app, we achieve this with the help of django signals.

We begin by creating a UserRegistrationModel class in our models.py file as seen below. This is simply a class containing a OneToOneField() with information relating to a specific user.

Next we create a signals.py file in our authapp as seen below. As defined in the official Django documentation, signals allow certain senders to notify a set of receivers that some action has taken place. Before being able to use signals ,we need to register them,so our application can load them at start up, we do this by using the def ready() method in our apps.py file whith in our authapp as seen below,

next in our app init.py file we do the following

The above simply loads the app config subclass

We conclude this by moving to our signals.py file ,doing all the necessary imports then creating a create_profile function seen below;

From the above, the post_save signal is being used which is triggered after a model finishes executing its save method. Basically this function creates a user instance for each new user after registration using the userRegistrationModel form.

We conclude our backend by moving to the main settings.py in our main project directory and input the following code;

LOGIN_REDIRECT_URL: This tells our app where to redirect a user after they login

EMAIL_FILE_PATH: This creates a folder in our project where all our user reset emails will be sent.

The lOGIN_URL and LOGOUT_URL are simply the namespaces for thelogin and logout in our authapp. This concludes our backend and now we move to our frontend.

The FrontEnd

We begin by setting up our base.html and navbar.html in our authapp templates folder from which all of our other .html files will inherit from.

This file begins with the {% load static %}which links to static files saved in the STATIC_ROOT.

Next we have our bootstrap, font awesome CDN .

The static template tag used here that is “{% load static %}” enables the css build the URL for the given relative path using the configured STATICFILES_STORAGE. Meanwhile the block content enables us to inherit all the attributes/styles in this file in other .html files. Finally the include tag imports the contents of the navbar.html into our base.html .

navbar.html

our navbar just like the rest of our front-end has been built using bootstrap-4. The “if statement” tells our app what parts of the navbar should be shown to the user if and when they are authenticated by our app. Remember the navbar.html file is in our templates folder directory.

login.html

In our template folder we create a registration folder within which we create a login.html file as seen below;

we begin here by using the extends tag which imports all the attributes of the base.html file then we load bootstrap4 package which will enable us to use an already design form saving us time

Within the block content we have an if statement which is self explanatory then a form which contains a url tag which returns and absolut path reference and a csrf_token which is a security feature implement by Django to safe guard our forms from cross-site forgery attacks.

Next in our templates folder we create an authapp directory to contain the rest of our .html files begining with the dashboard.html file below

dashboard.html

This file contains the {{welcome}} message from our dashboard function in the views.py file. Then url tags to edit our profile and change passwords

N.B: The authapp here refers to the app_name in the urls.py file and the edit and password_change are the names we gave to the url tags in urls.py

edit.html

This displays the form containing the fields we defined for the user to be capable of editing.

logged_out.html

This Displays the login screen to the user after they are logged out of their account.

password_change_form.html

Presents users with a form to change their password.

password_reset_complete.html

Informs user their password has been reset. Then provides them with a link to login.

password_reset_confirm.html

This will be displayed to the user after they click on the password reset link giving them the ability to reset their password else the {% else %} will be put into effect

password_reset_done.html

password_reset_email.html

sends a password reset link to the users email. A password reset file will be created in the send_emails directory. Rememeber we are using the django SMTP backend. Below is sample email,

password_reset_form.html

Presents the user a form to enter their email address in order to receive the password reset link.

register.html

This is the user registration form.

register_done.html

This page informs user of their newly created account.

Conclusion

Django is regarded as a web framework for perfectionist with a deadline and if you have ever wondered why this is so, I’m certain this tutorial has given you sufficient insight to further solidify this claim seen as how easy and time saving it was in building this application. Not leaving out the fact that Django in general has a very easy documentation for beginners to easily read ,understand and code along.

With all that been said, we have come to an end of our Tutorial. Be sure to check out our resource links below alongside our github repo for the source code and the appropriate credits.

Resources

python documentation

django documentation

bootstrap 4 documentation

font awesome

Django bootstrap4

--

--