0
0
DjangoHow-ToBeginner · 4 min read

How to Use Django Authentication: Simple Guide with Examples

Use Django's built-in django.contrib.auth system to handle user authentication by importing authenticate, login, and logout functions. These allow you to verify user credentials, start user sessions, and end them securely in your views.
📐

Syntax

Django authentication uses these main functions in your views:

  • authenticate(request, username, password): Checks if the username and password are correct and returns a user object or None.
  • login(request, user): Logs in the user by creating a session.
  • logout(request): Logs out the current user by clearing the session.
python
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import redirect

def user_login(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request, username=username, password=password)
    if user is not None:
        login(request, user)
        return redirect('home')
    else:
        return redirect('login')

def user_logout(request):
    logout(request)
    return redirect('login')
💻

Example

This example shows a simple login view that authenticates a user and logs them in, and a logout view that logs the user out.

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

# Login view

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('home')
        else:
            return render(request, 'login.html', {'error': 'Invalid credentials'})
    return render(request, 'login.html')

# Logout view

def user_logout(request):
    logout(request)
    return redirect('login')
Output
When a user submits correct credentials, they are redirected to 'home'. If credentials are wrong, the login page reloads with an error message. Logging out redirects to the login page.
⚠️

Common Pitfalls

  • Not calling authenticate before login can cause errors or security issues.
  • Forgetting to check if user is None after authentication leads to login failures.
  • Not using POST method for login data can expose credentials in URLs.
  • Not redirecting after login/logout can confuse users.
python
from django.contrib.auth import login

def wrong_login(request):
    user = request.user  # This is not authenticated user from credentials
    login(request, user)  # Wrong: user may not be authenticated

# Correct way
from django.contrib.auth import authenticate, login

def correct_login(request):
    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)  # Only login if user is authenticated
📊

Quick Reference

Remember these key points when using Django authentication:

  • Always use authenticate before login.
  • Use POST requests to send login data securely.
  • Use logout to end user sessions properly.
  • Redirect users after login/logout to improve user experience.
  • Use Django's built-in LoginView and LogoutView for simpler setups.

Key Takeaways

Use authenticate to verify user credentials before logging in.
Call login only with a valid authenticated user object.
Use logout to securely end user sessions.
Always handle login data via POST requests to keep credentials safe.
Redirect users after login or logout to guide their navigation.