User Authentication

  • Learn how to implement user authentication including login, logout, and registration in Django.
  • What is User Authentication?

    User Authentication is the process of:

    • Identifying a user

    • Verifying credentials (username & password)

    • Allowing access to protected pages

    Django provides a built-in authentication system.

    Django User Model

    What is the User Model?

    Django provides a default User model inside:

    django.contrib.auth.models


    It stores:

    • Username

    • Password (encrypted)

    • Email

    • Permissions

    • User status

    Default Fields in User Model

    Field

    Description

    username

    Unique login name

    password

    Hashed password

    email

    User email

    is_staff

    Admin access

    is_superuser

    Full permissions

    is_active

    Active/inactive user

Importing User Model

Import Djangoโ€™s built-in User model.

from django.contrib.auth.models import User

Creating Users

Create User Using Django Shell

python manage.py shell

from django.contrib.auth.models import User
User.objects.create_user(
    username='hinal',
    password='test1234',
    email='hinal@gmail.com'
)
  • create_user() automatically hashes the password.

    Login & Logout (Core Concepts)

    Authentication Flow

    User submits login form

            โ†“

    authenticate()

            โ†“

    login()

            โ†“

    User session created

    Login Functionality

Login View Using Django Authentication[views.py]

Authenticates user and logs them in.

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

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 redirect('dashboard')

    return render(request, 'login.html')
  • Explanation

    • authenticate() โ†’ verifies credentials

    • login() โ†’ creates user session

    Login Template

Login HTML Form

login.html

<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>
  • Logout Functionality

Logout View

Ends user session.

from django.contrib.auth import logout

def logout_view(request):
    logout(request)
    return redirect('login')
  • Protecting Views (Login Required)

Login Required Decorator

from django.contrib.auth.decorators import login_required

@login_required
def dashboard(request):
    return render(request, 'dashboard.html')
  • Redirects unauthenticated users to login page.

    Settings for Authentication

Authentication Settings

settings.py

LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'dashboard'
LOGOUT_REDIRECT_URL = 'login'

Access Logged-in User Data

request.user.username
request.user.email

  •  Available in views & templates.

    Authentication Using Django Forms

Using AuthenticationForm

from django.contrib.auth.forms import AuthenticationForm

def login_view(request):
    form = AuthenticationForm(request, data=request.POST or None)

    if form.is_valid():
        user = form.get_user()
        login(request, user)
        return redirect('dashboard')

    return render(request, 'login.html', {'form': form})
  • Common Authentication Errors

    Error

    Reason

    Solution

    Login fails

    Wrong password

    Check credentials

    User inactive

    is_active=False

    Activate user

    CSRF error

    Missing token

    Add {% csrf_token %}

    Real-World Example

  • Real-World Example 

    Simple Auth Flow

    1. User registers

    2. User logs in

    3. Access dashboard

    4. User logs out