Lesson 44 of 60 – Django User Authentication
73%

Django User Authentication

Authentication is the process of identifying a user and checking whether the user is allowed to access an application.

Django provides a built-in authentication system that includes users, password management, login, logout, permissions, groups, and sessions.

Note: Django's built-in authentication framework provides many features required for user login systems without building everything from scratch.

1. What is Authentication?

Authentication means verifying the identity of a user.

For example, when a user enters a username and password, the application checks whether the credentials are valid.

Username
   +
Password
   ↓
Authentication
   ↓
User Identified

2. Authentication vs Authorization

Authentication and authorization are related but different concepts.

Concept Meaning
Authentication Checks who the user is.
Authorization Checks what the user is allowed to do.

For example, logging in is authentication, while checking whether a user can access an admin page is authorization.

3. Django Authentication System

Django includes an authentication framework as part of its built-in functionality.

It provides features such as:

  • User accounts.
  • Password handling.
  • Login and logout.
  • Permissions.
  • Groups.
  • Sessions.
  • Authentication decorators and utilities.

4. Django User Model

Django provides a built-in User model through its authentication system.

from django.contrib.auth.models import User

The User model provides commonly required account information such as username, password, email, and permission-related information.

5. Built-in Authentication App

Django's authentication functionality is provided by django.contrib.auth.

The authentication application is normally included in INSTALLED_APPS in a new Django project.

INSTALLED_APPS = [

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

]

6. Authentication Migrations

Django's authentication system uses database tables for users, groups, permissions, and related information.

Run migrations to create the required database tables:

python manage.py migrate

After migration, the authentication system can store its database data.

7. Creating a Superuser

A superuser has all available permissions by default.

Create a superuser using:

python manage.py createsuperuser

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

8. Creating Users Programmatically

Django provides a user manager for creating users.

from django.contrib.auth.models import User

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

Use create_user() rather than directly storing a raw password on the User object.

9. Password Security

Django does not normally store user passwords as plain text. Its authentication system uses password hashing.

user.set_password(
    "newpassword"
)

user.save()

This is important when creating or changing passwords programmatically.

10. Checking Passwords

Django provides check_password() to verify a password against the stored password hash.

if user.check_password(
    "secret123"
):

    print("Password is correct")

The application should not compare passwords by reading or storing raw password values.

11. authenticate()

The authenticate() function checks the supplied credentials against configured authentication backends.

from django.contrib.auth import authenticate

user = authenticate(
    username="rahul",
    password="secret123"
)

if user is not None:

    print("Authentication successful")

else:

    print("Invalid credentials")

12. login()

After successfully authenticating a user, the login() function can associate the user with the current session.

from django.contrib.auth import login

login(
    request,
    user
)

The user can then be recognized as logged in during subsequent requests.

13. logout()

The logout() function removes the user's authentication information from the current session.

from django.contrib.auth import logout

logout(request)

It is commonly used by logout views.

14. Basic Login View

A simple login view can authenticate the submitted username and password.

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

def login_view(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 render(
        request,
        "login.html"
    )

15. Login Form HTML

A basic login form can contain username and password fields.

<form method="post">

    {% csrf_token %}

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

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

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

</form>

16. Checking request.user

Django provides request.user to access the user associated with the current request.

def dashboard(request):

    print(request.user)

If the user is authenticated, this represents the logged-in user.

17. is_authenticated

The is_authenticated attribute can be used to check whether the current user is authenticated.

if request.user.is_authenticated:

    print("User is logged in")

else:

    print("User is not logged in")

This is useful for controlling access to pages and displaying different content.

18. login_required Decorator

The login_required decorator can restrict a view to authenticated users.

from django.contrib.auth.decorators import (
    login_required
)

@login_required
def dashboard(request):

    return render(
        request,
        "dashboard.html"
    )

Unauthenticated users are redirected according to the configured login URL behavior.

19. Setting LOGIN_URL

You can configure the login page used by authentication redirects.

LOGIN_URL = "/login/"

This setting is commonly used with login_required.

20. User Permissions

Django includes a permission system for controlling what users can do.

Permissions can be associated with actions such as:

  • Add records.
  • Change records.
  • Delete records.
  • View records.

Permissions can be assigned to users or groups.

21. Checking a Permission

You can check whether a user has a particular permission.

if request.user.has_perm(
    "students.view_student"
):

    print("Permission granted")

The permission name normally follows the format:

app_label.permission_codename

22. Django Groups

Groups allow permissions to be assigned to multiple users together.

For example:

Administrators
Teachers
Students

Instead of assigning the same permissions to every user individually, you can assign permissions to a group and add users to that group.

23. Checking Group Membership

A user's groups can be checked through the user's relationship with groups.

if request.user.groups.filter(
    name="Teachers"
).exists():

    print("Teacher user")

This can be useful when different users should see different features.

24. Authentication and Sessions

Django authentication works together with sessions to remember authenticated users between requests.

After:

login(request, user)

Django associates the authenticated user with the current session.

This allows later requests to access the user through request.user.

25. Built-in Authentication URLs

Django provides built-in authentication views that can be included in a project.

from django.urls import include, path

urlpatterns = [

    path(
        "accounts/",
        include(
            "django.contrib.auth.urls"
        )
    ),

]

This can provide standard routes for features such as login, logout, and password management when the corresponding templates are provided.

26. Password Management

Django's authentication system includes password management features.

  • Password change.
  • Password reset.
  • Password reset email workflow.
  • Password hashing.
  • Password validation.

These features can be used instead of building password handling from scratch.

27. Custom User Model

Django allows projects to use a custom user model when the application's requirements differ from the default User model.

A custom user model is commonly configured through:

AUTH_USER_MODEL = "accounts.User"

When using a custom user model, it is important to plan this choice early in a project because changing user-model relationships later can require additional migration work.

28. Complete Authentication Workflow

User opens login page
        ↓
User enters username/password
        ↓
POST request
        ↓
authenticate()
        ↓
Credentials valid?
     ↙          ↘
   Yes           No
    ↓             ↓
 login()       Show error
    ↓
Session created
    ↓
Protected page
    ↓
request.user

This is the basic flow used by many Django login systems.

29. Common Authentication Mistakes

  • Storing passwords as plain text.
  • Not using Django's password handling functions.
  • Forgetting authenticate() before login.
  • Calling login() without a successfully authenticated user.
  • Forgetting {% csrf_token %} in internal POST login forms.
  • Not protecting private pages with appropriate access checks.
  • Forgetting to configure authentication URLs or templates.
  • Confusing authentication with authorization.
  • Changing a custom user model late in a project without planning migrations.

30. Django Authentication Summary

Django provides a complete authentication framework for managing users and access to applications.

  • authenticate() verifies supplied credentials.
  • login() associates an authenticated user with the session.
  • logout() ends the authenticated session.
  • request.user provides the current user.
  • is_authenticated checks authentication status.
  • login_required protects views.
  • Permissions control access to specific actions.
  • Groups allow permissions to be managed for multiple users.
  • Django provides password hashing and password-management features.
  • Projects can use a custom user model when needed.

📌 Key Points

  • Authentication verifies the identity of a user.
  • Django provides a built-in authentication framework.
  • authenticate() checks credentials.
  • login() logs an authenticated user into the current session.
  • logout() logs the current user out.
  • request.user represents the current user.
  • login_required can protect private views.
  • Permissions and groups provide authorization features.
  • Django handles password hashing rather than storing raw passwords.
  • Django supports custom user models for applications with specialized requirements.

🧠 Quick Quiz

Question: Which Django function is used to verify a user's credentials?