Authentication Overview

Django ships a complete authentication system with users, sessions and permissions.

Django includes a full authentication system in django.contrib.auth: a User model, login/logout, password hashing, permissions and groups. Requests carry the logged-in user as request.user, populated by the authentication middleware.

Middleware processes every request on the way in and every response on the way out.

An incoming request passes down through the middleware stack to the view, and the response travels back up through the same middlewareRequest inSecurityMiddlewareSessionMiddlewareAuthenticationMiddlewareViewrequestresponse
Middleware wraps every request and response, in order.

Example

Example Β· python
# request.user is available in every view and template
def dashboard(request):
    if request.user.is_authenticated:
        return HttpResponse(f"Hi {request.user.username}")
    return HttpResponse("Please log in")

# In templates:
# {% if user.is_authenticated %} ... {% endif %}

When to use it

  • A developer relies on Django's built-in auth system to handle user registration, login, and password hashing.
  • A team adds 'django.contrib.auth' to INSTALLED_APPS to get User, Group, and Permission models for free.
  • A developer uses request.user throughout views and templates to know who is making each request.

More examples

Check authentication in a view

Checks request.user.is_authenticated to redirect unauthenticated visitors to the login page.

Example Β· python
def dashboard(request):
    if not request.user.is_authenticated:
        return redirect("login")
    return render(request, "dashboard.html", {"user": request.user})

Access user in a template

Uses the automatically available 'user' context variable to show different UI for logged-in users.

Example Β· html
{% if user.is_authenticated %}
  <p>Hello, {{ user.get_full_name|default:user.username }}!</p>
  <a href="{% url 'logout' %}">Log out</a>
{% else %}
  <a href="{% url 'login' %}">Log in</a>
{% endif %}

Include Django's auth URLs

Mounts all of Django's built-in authentication URL patterns under the /accounts/ prefix.

Example Β· python
# mysite/urls.py
from django.urls import path, include

urlpatterns = [
    path("accounts/", include("django.contrib.auth.urls")),
    # Provides: login, logout, password_change, password_reset, ...
]

Discussion

  • Be the first to comment on this lesson.
Authentication Overview β€” Django | SoundsCode