User Authentication System in Django Python

django logo

What we will learn?

Before we learn about the User Authentication System in Django Python, let’s first see what we did until now in the previous part of our series, we made a blog app, added a model, made some templates, ran migrations, and posted our first blog on our website. I also added a place for an about page in the template but didn’t actually register it our views or URLs. This was because I wanted you guys to practice out how to make a webpage in Django. Just follow the same methods we did to make our home page, and create the about all by yourself. If you haven’t checked my previous post then here you go.

In this part of our series, we will be creating a User Authentication System in Django for our Blog site. The “User authentication system” might look something big and complicated, but actually, it’s not.


What is User Authentication System?

A user authentication system is how our website responds when a new person registers or a registered user logs in to our website, or someone logs out of our website and all such related things. So we will make a complete structure to handle all these things for our website. We will do this in a new app, in which we will put all the user-related code. So, let’s start with our first step in the journey of the User Authentication System in Django Python.

assignment advertisement

Creating a new app

Open up your terminal and activate your virtual environment. Previously we created an by using the “Django-admin startapp blog” command, but this time we will be using our manage.py file to create an app. You can do it either way you want. So the command is:

> python manage.py startapp users

I named the app ‘users’, as it will handle all our user-related data, you can name it the same or any other name suitable to you.


Registering our app in settings.py file

As we saw at the beginning of our series, all our apps and 3rd party modules need to be registered in the settings.py file. So, open your project folder in a text editor, then in the settings.py file, in the INSTALLED_APPS list, add your app’s name.

INSTALLED_APPS = [

     'blog',

    'users',

    'django.contrib.admin',

    'django.contrib.auth',

    'django.contrib.contenttypes',

     'django.contrib.sessions',

     'django.contrib.messages',

     'django.contrib.staticfiles',

]

So, the next thing we will do to start with our user authentication system is that we will create a register page for new users to register on our website. We will create a view in views.py file, a form to be filled by our users to register on our website, and a URL route. So, let’s get our hands on this.


Forms.py

Now as we are diving into the forms, what we are going to do is, we will inherit from the built-in Django UserCreationForm class, which is basically a built-in class that lets you create new users on your website. So, we will inherit this class and some more fields in it, and save these forms in a separate file “forms.py”. So now create a file and name it forms.py. Then add the following code:

from django import forms

from django.contrib.auth.models import User

from django.contrib.auth.forms import UserCreationForm

class UserRegisterForm(UserCreationForm):

    email = forms.EmailField()

    class Meta:

        model = User

        fields = ['username', 'email', 'password1', 'password2']

So, what’s happening here is we imported the forms module from Django. We also have the User class, which we used in the models.py file in the blog app previously to create our Post model. Then we also imported the UserCreationForm and inherited it in a class called UserRegisterForm. Then I added the email field using the EmailField class from the forms module.

The next we did is that we added another class called Meta. The Meta class in Django is a built-in class that helps us to make configurations to the defaults and keep them in one place. Then we specified the model to which this information is going to be saved, and of course, it is the User class, because all this information here is to register our new users. Then we specified the fields which we want for this form and in what order. We have a username field, an email field, a password field, and another password field to confirm the password.


Creating a view for register page

In the users app, open your views.py file. We will create a view that will validate our form, and if it is valid, then it will save it and give us a message that the user has been registered. To do this add the following lines of code to your views.py file in the users app:

from django.shortcuts import redirect, render

from django.contrib import messages

from .forms import UserRegisterForm

def register(request):

    if request.method == "POST":

        form = UserRegisterForm(request.POST)

        if form.is_valid():

            form.save()

            username = form.cleaned_data.get('username')

            messages.success(

                requestf'Hi {username}, Your account has been created successfully, you can now log in !!'

            )

            return redirect('blog-home')

    else:

        form = UserRegisterForm()

    return render(request, 'users/register.html', {'form': form})

Lines 1-3: We already know what redirect and render functions are for, the ‘messages’ module is a module built-in Django used to display messages on webpages such as an alert message or an error message etc. I also imported the UserRegisterForm we created from our forms.py file.

Lines 5-9 I created a register function and passed the request as a parameter. So, using an if statement, we verified if the request is a POST request. If you don’t know what are HTTP requests then check out this article to have an understanding of it. Then if our form is valid, we are going to save it.

Lines 10-15: Then I created a variable to get the username of our user, and display a success message that your account has been registered. Then we redirect the users to the login page which we haven’t created yet, but we will make next.

Lines 16-18: After that, if the form submitted is not a post request, then it will create a blank form.


Adding messages to the base template

In our views.py file of the users app, we added messages to inform our users that the account has been registered. But Django doesn’t know where to display the messages. I think a very good place for it would be the base template in our blog app, as we are extending this file in almost every template we have created or going to create. So, in your blog app, in the templates folder, open your base.html file, and right above the content block we created then, add the following code:

    <div class="col-md-5">

        {% if messages %}

        {% for message in messages %}

          <div class="alert alert-{{ message.tags }}">

              {{ message }}

          </div>

          {% endfor %}

        {% endif %}

        {% block content %}{% endblock %}

    </div>

I showed you guys the whole div tag so you can see where to add the code. What we doing here is that if there are any messages, then loop over them and display them one by one.


URL route for register page

We still haven’t created a URL route for our register page so let’s do it now. In users app create a file and name it urls.py. Copy the whole urls.py file in the blog app, and paste it into your users url.py file. Empty the urlpatterns list, and add the following line to it.

urlpatterns = [

    path('register/', views.register, name='register')

]

Now we need to register our users url.py file in the project url.py file. To do this open your main project folder, in my case it is django_project, and in the urlpatterns list of urls.py file add the following code:

urlpatterns = [

    path('admin/', admin.site.urls),

    path('', include('blog.urls')),

    path('', include('users.urls')),

]

After working so much with URLs, you should now get a good idea of how does all this work.


Register template

We still haven’t created a template for our register view, so in the users app creates a folder and name it templates, then makes another folder in the templates folder and name it ‘users’. In the users folder create a file and name it ‘register.html’. Now copy the HTML code from GitHub.

Now if you have seen the register.html file on my GitHub, you will see that the 2nd line says ‘{% load crispy_form_tags %}. ‘Crispy forms’ is a 3rd part module that adds some CSS to give our form a look without writing extra code. As this is a 3rd party module, you will need to install it first. So, fire up your terminal and make sure to activate your virtual environment which we created at the beginning of the series. Then type:

> pip install django-crispy-forms

Now we are done with the installation, as this is a 3rd party module, we need to add it to the INSTALLED_APPS list in the settings.py file. So in the settings.py file, in the INSTALLED_APPS list add:

‘crispy_forms’,

Now your list should be looking like this:

INSTALLED_APPS = [

    'blog',

    'users',

    'crispy_forms',

    'django.contrib.admin',

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.messages',

    'django.contrib.staticfiles',

]

You can add it where ever you want to the list. But crispy forms by default uses Bootstrap 2 which is quite outdated now, So we have to make it use Bootstrap 4. To do this, in the settings.py file, go all the way to the bottom and add:

CRISPY_TEMPLATE_PACK = 'bootstrap4'

This should do it for using bootstrap 4.

Now that we have created our register page, we also need a login and logout page. So next we will make a login page with which our registered users will be able to log in, and a logout page, so our users will be able to log out from our website.


Templates

Let’s start by making templates for both our login page and logout page. You can get the templates from my GitHub. Add them to the templates/users folder of your users app.


Log in and Logout views

For our register page, we configured the UserCreationForm class and made some more additions and changes to it, but for our login and logout views, we are going to use the built-in Django login and log-out views. So in your urls.py file of users app add the following lines of code:

from django.urls import path

from . import views

from django.contrib.auth import views as auth_views

urlpatterns = [

    path('register/', views.register, name='register'),

    path('login/', auth_views.LoginView.as_view(template_name = 'users/login.html'), name='login'),

    path('logout/', auth_views.LogoutView.as_view(template_name = 'users/logout.html'), name='logout'),

]

What’s new here is the import I did to get the built-in Django views as auth_views.  I named it auth_views so the names don’t collide with the views from our views.py file. In the urlpatterns, I have added the login and logout routes, and the built-in views of Django for login and log out. These are class-based views, and we haven’t seen them yet, but we will see them soon when we will make some of them later in the series. These built-in views will handle all the forms and logic by themselves so we don’t have to write any extra code for it.


Running the Server

Now if you try running the server (in the terminal type: python manage.py runserver), you should land on your website without any errors. Now try accessing the register page from your search-bar (add /register to the url in your search bar).

register page

If you have done no errors then you should be able to access the register page of your website. Try making an account with it. You will be redirected to the home page. Now try accessing the login page. As you submit it you get the following error:

Error 404

It is because Django is searching for the route accounts/profile and it doesn’t exist, although we are logging in successfully. To solve this error, open your settings.py file, and at the bottom add this line:

LOGIN_REDIRECT_URL = 'blog-home'

This means that instead of redirecting us to accounts/profiles, redirect us to our blog-home route which is our home page. After doing this try logging in again and you should be directed to our home page. Now try logging out from your search bar.

Logout page

You should be logged out successfully.

Right now, our website doesn’t give us a good response when we log in or log out from it, but we will fix this now.


Base.html

Open your base template in your blog app, and go all the way to where it says ‘NavBar Right Side’. As the login and logout links are blank, we will add our url routes to them.

<!-- Navbar Right Side -->

<div class="navbar-nav">

    <a class="nav-item nav-link" href="{% url 'login' %}">Login</a>

    <a class="nav-item nav-link" href="{% url 'register' %}">Register</a>

</div>

Now it has our url routes but it is a bit weird to show the registered route to a user who has already logged in. Instead, we need to show him a logout link so he can log out easily without using the search bar. To do this we need to add some if-else statements in our base.html file. So instead of the above <div> add the following code:

<div class="navbar-nav">
{% if user.is_authenticated %}
       <a class="nav-item nav-link" href="{% url 'logout' %}">
       Logout
       </a>
{%else %}
       <a class="nav-item nav-link" href="{% url 'login' %}">
       Login
       </a>
       <a class="nav-item nav-link" href="{% url 'register' %}">
       Register
       </a>
       {% endif %}
</div>

We will add some more links later on such as ‘New post’ for our authenticated users etc. but for now we are all set. After saving all this, run your development server, and try logging in. It will now give you only one link which is the logout link. Now log out by clicking it. You will again get the register and login links.

You can also check all your registered users and posts from the Django administration page.

django admin page


User Authentication System in Django Python | Summary

In this part of our series, we created a User Authentication System in Django Python for our website. Now our website has the ability to register, log in, and log out our users. We also saw how Django’s built-in functions and classes are very helpful in writing less code.

In the upcoming part of our series, we will see how to create a profile page for our users and adding pictures to their profiles, and much more.

Stay tuned and keep coding !!

Also, let us know if you find any difficulty in our User Authentication System in Django Python article, we will try our best to help you.

Thank you for reading.


Also Read:



Share:

Author: Ayush Purawr