In this blog article, we will take an overview of Django’s authentication system, and how we can use that for user registration and login. Django provides a robust authentication system for easy user management. And we can also customize it as per our requirements.

Django provides a customizable user authentication system out of the box. We can directly use it for user management along with Django’s default forms and routes. Django also provides routes and forms, so we can easily take full advantage of it without any customization.

For this tutorial, we are using the latest version of Django. Let’s start,

Setting up the Project

Step 1

First, let’s create a virtual environment for the project, to create a virtual environment, open the terminal at your desired location and run the below command, the below command will also activate the newly created environment.

python3 -m venv env && source env/bin/activate

Step 2

Now install the Django.

pip install django

Step 3

Create a new Django project with the below command. ‘django_auth_demo’ is a project name.

django-admin startproject django_auth_demo

Now run the below command to change the project directory and create a new Django app within the project directory.

cd django_auth_demo && django-admin startapp users

Configuring Django Project

Step 4

Open your project folder with any text editor and open the setting.py inside the django_auth_demo folder. We need to register the new Django app that we have created. To do that update the ‘INSTALLED_APPS’ list in the setting file as described below.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'users', # New
]

Step 5

Now, run the migrations to create the database. For the demo, we are using the SQLite database (the default database of Django). You can also use any other SQL database that Django supports. To run the migrations, run the below command in your terminal.

python manage.py migrate

User Registration

Step 6

Now open the users/views.py file and add the below code to the file.

# users/views.py
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

def register_user(request):
    form = UserCreationForm()
    content = {'form': form}
    return render(request, 'register.html', content)

In the code, we created a new route for user registration. For the form, we are using the default Django form for user registration. Because the default form has good validations, so we don’t need to set it manually.

Step 7

Now create a new folder ‘templates’ under the ‘users’ folder. Also, create the new file ‘register.html’ in the templates folder. The file path should be like ‘users/templates/register.html’. Now open the register.html file and add the below HTML code to display the Django form on the page.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register user</title>
</head>
<body>
    <h1>Register user</h1>
    <form action="" method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Submit">
    </form>
</body>
</html>

Step 8

Now open the urls.py file in the ‘django_auth_demo’ folder and update the file as described below.

# django_auth_demo/urls.py
from django.contrib import admin
from django.urls import path
from users.views import register_user # New

urlpatterns = [
    path('admin/', admin.site.urls),
    path('register/', register_user), # New
]

Running the Django Server

Step 9

Save all the files and run the below command in the terminal to start the Django server.

python manage.py runserver

Now open “http://localhost:8000/register/” in your browser. This page should display the registration form.

Now to perform the user registration, we again need to update our view function to save the form data in the database. Open the users/views.py file and update the register_user function as described below. The below code will validate the form and save it in the database. If there are any errors in the validation, it will be also displayed on the HTML page.

def register_user(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid(): # Validate the form before saving it.
            form.save()
        else:
            # If there are any errors in the form, render the same form again to display validation errors.
            return render(request,'register.html', {'form': form})

    form = UserCreationForm()
    content = {'form': form}
    return render(request, 'register.html', content)

User Login

Step 10

Now refresh the page (http://localhost:8000/register/) fill in all the required information, and submit. This should register the new user. Now we need to create the login functionality. For that again open the users/views.py file in a text editor and add the required imports at the top of the file after existing imports.

from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth import authenticate, login
from django.http import HttpResponse

Now add the login view function at the bottom of the file.

def login_user(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        try:
            user_details = User.objects.get(username = username)
            user = authenticate(request, username=username, password=password) # Check the username and password
            if user is not None:
                login(request, user) # Login the user and return Http response.
                return HttpResponse("Login Success")
            else:
                return render(request, 'login.html', {'message': 'Invalid Credentials'})
        except ObjectDoesNotExist:
            return render(request,'login.html', {'message': 'User does not exist'})

    context = {}
    return render(request,'login.html', context=context)

Now create the new file ‘login.html’ in the templates folder. The file path should be like ‘users/templates/login.html’. Now open the login.html file and add the below HTML code to the file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login page</title>
</head>
<body>
    <h1>Login page</h1>
    <form method="post" action=''>
        {% csrf_token %}
        <label>username</label>
        <input type="text" name="username" aria-label="username"><br>
        <label>password</label>
        <input type="password" name="password" aria-label="password"><br>
        <input type="submit" value="Login">
    </form>
    {{message}}
</body>
</html>

Step 11

Now open the urls.py file and update it as described below

from django.contrib import admin
from django.urls import path
from users.views import register_user, login_user # New

urlpatterns = [
    path('admin/', admin.site.urls),
    path('register/', register_user),
    path('login/', login_user), # New
]

Step 12

Now save all the files and open http://localhost:8000/login/ in your browser. This should display the login page.

Here, add your username and password, and you will be able to log in. If the username and password are correct, you will be able to see the login success on the page. and if there are any errors, it will be displayed on the page itself.

With the help of the authentication and login functions of Django, you can easily perform user authentication. For the login functionality, we have not created any Django forms for demo purposes.

To make any route accessible only for authenticated users only you can use the login_required decorator at the top of the route function. You can find more information about this in Django’s official docs here. You can make a new route with the login_required decorator and redirect the user to that page instead of displaying the message on the same page.

You can access the entire code on the below git repo for reference.

Github Link: https://github.com/mittalpatel/blog-django-auth-demo-basic

Conclusion

This tutorial has walked you through the seamless integration of Django’s authentication system for user registration and login. With clear steps, code snippets, and visual aids, you’ve learned to harness the power of Django’s default forms and routes, empowering you to implement robust user authentication in your projects efficiently. Explore the provided GitHub repository for a comprehensive reference.


Seeking expert assistance in Django development? Contact us or share your requirements at letstalk@pragnakalp.com to get an expert consultation!

Categories: Django How To

Leave a Reply

Your email address will not be published.

You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*