Lesson 57 of 60 – Django Authentication Project
95%

Django Authentication Project

Authentication is one of the most important parts of a real-world web application. It allows users to create accounts, log in, log out, and access pages that require authentication.

In this lesson, we will build a practical Django Authentication Project using Django's built-in authentication system. We will cover registration, login, logout, protected pages, sessions, password handling, and basic user management.

Note: Django provides a built-in authentication framework with a secure User model, password hashing, authentication functions, sessions, permissions, and decorators such as login_required.

1. What is Authentication?

Authentication is the process of verifying the identity of a user.

For example, when a user enters a username and password, the application checks whether those credentials belong to a valid account.

Username
    +
Password
    ↓
Authentication
    ↓
User Account

2. Authentication vs Authorization

Authentication and authorization are related but different concepts.

  • Authentication: Who are you?
  • Authorization: What are you allowed to do?

For example, a user may successfully log in but may not have permission to delete another user's post.

3. Django Authentication System

Django includes a built-in authentication framework.

The authentication system provides:

  • User accounts
  • Password management
  • Login
  • Logout
  • Sessions
  • Permissions
  • Groups
  • Password validation

4. Built-in User Model

Django provides a built-in User model through django.contrib.auth.models.

from django.contrib.auth.models import User

The User model provides fields and functionality for managing user accounts.

5. Authentication App

Django projects normally include the authentication application in INSTALLED_APPS.

INSTALLED_APPS = [

    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",

]

These built-in applications provide authentication and session support.

6. Run Authentication Migrations

Run migrations to create the database tables required by Django's built-in authentication system.

python manage.py migrate

This creates tables for users, permissions, groups, sessions, and other built-in Django components.

7. Create a Superuser

Create a Django administrator account using:

python manage.py createsuperuser

Django will ask for information such as username, email, and password.

8. Create Users Programmatically

A user can also be created from Python code.

from django.contrib.auth.models import User

user = User.objects.create_user(
    username="rahul",
    email="rahul@example.com",
    password="StrongPassword123"
)

Use create_user() rather than assigning a raw password directly to the password field.

9. Password Security

Django does not normally store user passwords as plain text. Django's authentication system handles password hashing and verification.

For example:

user.set_password(
    "NewPassword123"
)

user.save()

This should be used when setting or changing a user's password.

10. Create Registration Form

A simple registration form can use Django's User model.

from django import forms
from django.contrib.auth.models import User

class RegistrationForm(forms.ModelForm):

    password = forms.CharField(
        widget=forms.PasswordInput
    )

    class Meta:

        model = User

        fields = [
            "username",
            "email",
            "password"
        ]

For production applications, password validation and confirmation fields should also be handled carefully.

11. Registration View

The registration view receives user information and creates an account.

from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from django.contrib import messages

def register(request):

    if request.method == "POST":

        username = request.POST.get(
            "username"
        )

        email = request.POST.get(
            "email"
        )

        password = request.POST.get(
            "password"
        )

        User.objects.create_user(
            username=username,
            email=email,
            password=password
        )

        messages.success(
            request,
            "Account created successfully."
        )

        return redirect(
            "login"
        )

    return render(
        request,
        "accounts/register.html"
    )

12. Registration Template

<h2>
Create Account
</h2>

<form method="post">

    {% csrf_token %}

    <input
        type="text"
        name="username"
        placeholder="Username"
        required
    >

    <input
        type="email"
        name="email"
        placeholder="Email"
        required
    >

    <input
        type="password"
        name="password"
        placeholder="Password"
        required
    >

    <button type="submit">
        Register
    </button>

</form>

13. Checking Username Availability

Before creating a user, you can check whether the username already exists.

if User.objects.filter(
    username=username
).exists():

    messages.error(
        request,
        "Username already exists."
    )

This prevents duplicate usernames from causing registration problems.

14. Authenticate a User

Django provides the authenticate() function for checking user credentials.

from django.contrib.auth import authenticate

user = authenticate(
    username=username,
    password=password
)

If the credentials are valid, Django returns the authenticated user. Otherwise, it returns None.

15. Login User

After successful authentication, use Django's login() function to create the authenticated session.

from django.contrib.auth import login

login(
    request,
    user
)

The user can then access authenticated pages.

16. Complete Login View

from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.contrib import messages

def user_login(request):

    if request.method == "POST":

        username = request.POST.get(
            "username"
        )

        password = request.POST.get(
            "password"
        )

        user = authenticate(
            request,
            username=username,
            password=password
        )

        if user is not None:

            login(
                request,
                user
            )

            return redirect(
                "dashboard"
            )

        messages.error(
            request,
            "Invalid username or password."
        )

    return render(
        request,
        "accounts/login.html"
    )

17. Login Template

<h2>
Login
</h2>

<form method="post">

    {% csrf_token %}

    <input
        type="text"
        name="username"
        placeholder="Username"
        required
    >

    <input
        type="password"
        name="password"
        placeholder="Password"
        required
    >

    <button type="submit">
        Login
    </button>

</form>

18. Logout User

Django provides the logout() function.

from django.contrib.auth import logout

def user_logout(request):

    logout(request)

    return redirect(
        "login"
    )

The user's authentication session is cleared.

19. Protect a View with login_required

The login_required decorator protects a view from unauthenticated users.

from django.contrib.auth.decorators import login_required

@login_required
def dashboard(request):

    return render(
        request,
        "accounts/dashboard.html"
    )

If the user is not logged in, Django redirects the request to the configured login URL.

20. Configure LOGIN_URL

The login URL can be configured in settings.py.

LOGIN_URL = "/login/"

This tells Django where users should be redirected when authentication is required.

21. Access the Current User

Django provides the current user through request.user.

def dashboard(request):

    print(
        request.user
    )

    return render(
        request,
        "accounts/dashboard.html"
    )

In an authenticated view, request.user represents the logged-in user.

22. Check Authentication Status

Use is_authenticated to check whether the current user is authenticated.

if request.user.is_authenticated:

    print("User is logged in")

In templates:

{% if user.is_authenticated %}

    Welcome, {{ user.username }}

{% endif %}

23. Display Login and Logout Links

{% if user.is_authenticated %}

    <p>
        Welcome {{ user.username }}
    </p>

    <a href="{% url 'dashboard' %}">
        Dashboard
    </a>

    <a href="{% url 'logout' %}">
        Logout
    </a>

{% else %}

    <a href="{% url 'login' %}">
        Login
    </a>

    <a href="{% url 'register' %}">
        Register
    </a>

{% endif %}

24. Authentication URL Patterns

from django.urls import path
from . import views

urlpatterns = [

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

    path(
        "login/",
        views.user_login,
        name="login"
    ),

    path(
        "logout/",
        views.user_logout,
        name="logout"
    ),

    path(
        "dashboard/",
        views.dashboard,
        name="dashboard"
    ),

]

25. Authentication Project Structure

auth_project/
│
├── manage.py
│
├── auth_project/
│   ├── settings.py
│   ├── urls.py
│   ├── asgi.py
│   └── wsgi.py
│
└── accounts/
    ├── migrations/
    ├── templates/
    │   └── accounts/
    │       ├── register.html
    │       ├── login.html
    │       └── dashboard.html
    │
    ├── __init__.py
    ├── admin.py
    ├── apps.py
    ├── forms.py
    ├── models.py
    ├── urls.py
    ├── views.py
    └── tests.py

26. Authentication Workflow

Register
   ↓
Create User
   ↓
Login
   ↓
Authenticate Credentials
   ↓
Create Session
   ↓
Access Protected Page
   ↓
Logout
   ↓
Session Ends

This is the basic flow of a Django authentication system.

27. Password Validation

Django provides password validators that can be configured in AUTH_PASSWORD_VALIDATORS.

The default project configuration can include validators for:

  • Password similarity
  • Minimum length
  • Common passwords
  • Numeric-only passwords

These validators can help enforce stronger password requirements.

28. Common Authentication Mistakes

  • Storing passwords as plain text.
  • Using raw password assignment instead of password helpers.
  • Forgetting {% csrf_token %} in POST forms.
  • Forgetting to run migrations.
  • Forgetting to configure the login URL.
  • Forgetting to use login() after authentication.
  • Not protecting private views.
  • Using incorrect URL names.
  • Not handling invalid login credentials.
  • Allowing unauthorized users to access management pages.

29. Complete Authentication Project Flow

User Registration
        ↓
User Account Created
        ↓
Login Form
        ↓
authenticate()
        ↓
login()
        ↓
Session Created
        ↓
Dashboard
        ↓
login_required
        ↓
Protected Content
        ↓
logout()
        ↓
Login Page

30. Django Authentication Project Summary

The Django Authentication Project combines Django's built-in authentication tools to create a complete user access system.

  • Use the built-in User model for user accounts.
  • Use create_user() to create users.
  • Use authenticate() to verify credentials.
  • Use login() to create an authenticated session.
  • Use logout() to log a user out.
  • Use login_required to protect views.
  • Use request.user to access the current user.
  • Use is_authenticated to check login status.
  • Use Django's password handling instead of storing raw passwords.
  • Use permissions and groups when different levels of access are required.

📌 Key Points

  • Django provides a complete built-in authentication framework.
  • authenticate() checks user credentials.
  • login() creates an authenticated session.
  • logout() ends the user's authenticated session.
  • login_required protects private views.
  • request.user provides the current user.
  • Django handles password hashing through its authentication system.
  • Authentication and authorization are different concepts.

🧠 Quick Quiz

Question: Which Django function is used to verify a username and password?