User Authentication
Authentication answers the question "who is this user?". Django's built-in auth app gives you user accounts, secure password storage, login and logout views and tools for restricting pages, so students can sign up and RSVP to Campus Events.
What Django gives you
- A
Usermodel withusername,password,email,first_name,last_name,is_active,is_staffandis_superuser. - Password hashing: passwords are never stored as plain text, only as a salted hash (PBKDF2 by default).
- Ready-made views for login, logout, password change and password reset.
request.userin every view anduserin every template.
All of this is switched on in a new project through django.contrib.auth in INSTALLED_APPS and the session and authentication middleware.
For a real project you're starting from scratch, the Django docs recommend setting up a custom user model (AUTH_USER_MODEL) before your first migrate, even if it's identical to the default. It's hard to switch later. For learning, the default User is fine.
Step 1: Add the built-in auth URLs
campus/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("admin/", admin.site.urls),
path("accounts/", include("django.contrib.auth.urls")),
path("accounts/", include("accounts.urls")),
path("events/", include("events.urls")),
]
That first include() adds these named URLs (among others):
| URL | Name | Template it uses |
|---|---|---|
accounts/login/ | login | registration/login.html |
accounts/logout/ | logout | none needed if you set a redirect |
accounts/password_change/ | password_change | registration/password_change_form.html |
accounts/password_reset/ | password_reset | registration/password_reset_form.html |
Behind these URLs are class-based views such as LoginView and LogoutView. Tell Django where to send users afterwards:
campus/settings.py
LOGIN_REDIRECT_URL = "events:event_list" LOGOUT_REDIRECT_URL = "events:event_list"
Step 2: The login template
LoginView supplies the form; you supply the template.
templates/registration/login.html
{% extends "base.html" %}
{% block title %}Log in | {{ block.super }}{% endblock %}
{% block content %}
<h1>Log in</h1>
<form method="post">
{% csrf_token %}
{{ form }}
<input type="hidden" name="next" value="{{ next }}">
<button type="submit">Log in</button>
</form>
<p>New here? <a href="{% url 'signup' %}">Create an account</a></p>
{% endblock %}
The hidden next field sends users back to the page they were trying to reach before being asked to log in.
request.user set; logging out (by POST) clears it.Step 3: Logging out with a POST form
Since Django 5.0, LogoutView only accepts POST requests, so a malicious link or image can't log your users out. Put a small form in the navigation of your base template:
templates/base.html (inside <nav>)
{% if user.is_authenticated %}
<span>Hi, {{ user.username }}</span>
<form method="post" action="{% url 'logout' %}">
{% csrf_token %}
<button type="submit">Log out</button>
</form>
{% else %}
<a href="{% url 'login' %}">Log in</a>
<a href="{% url 'signup' %}">Sign up</a>
{% endif %}
Using an ordinary link, <a href="{% url 'logout' %}">Log out</a>. That sends a GET request, and Django 5 responds with 405 Method Not Allowed. Use a POST form with {% csrf_token %}; you can style the button to look like a link with CSS.
Step 4: A sign-up page
Django has no built-in sign-up view, but it provides UserCreationForm, which asks for a username and a password twice and validates password strength. Create an accounts app for it (python manage.py startapp accounts, then add "accounts" to INSTALLED_APPS).
accounts/views.py
from django.contrib.auth import login
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import redirect, render
def signup(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user) # log them in straight away
return redirect("events:event_list")
else:
form = UserCreationForm()
return render(request, "registration/signup.html", {"form": form})
accounts/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("signup/", views.signup, name="signup"),
]
The template templates/registration/signup.html looks just like the login template, with a "Sign up" heading and button.
Step 5: Restricting pages to logged-in users
Use the @login_required decorator on function views and LoginRequiredMixin on class-based views. Anonymous visitors are redirected to /accounts/login/?next=/the/page/. Here's an RSVP view that lets a logged-in student join or leave an event:
events/views.py
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, redirect
from django.views.decorators.http import require_POST
from .models import Event
@login_required
@require_POST
def rsvp(request, pk):
event = get_object_or_404(Event, pk=pk)
if event.attendees.filter(pk=request.user.pk).exists():
event.attendees.remove(request.user)
messages.info(request, "You're no longer attending.")
elif event.attendees.count() >= event.capacity:
messages.error(request, "Sorry, this event is full.")
else:
event.attendees.add(request.user)
messages.success(request, f"You're going to {event.title}!")
return redirect(event)
Add path("<int:pk>/rsvp/", views.rsvp, name="rsvp") to events/urls.py and a button to the detail page:
{% if user.is_authenticated %}
<form method="post" action="{% url 'events:rsvp' event.pk %}">
{% csrf_token %}
<button type="submit">RSVP / cancel RSVP</button>
</form>
{% else %}
<p><a href="{% url 'login' %}?next={{ request.path }}">Log in</a> to RSVP.</p>
{% endif %}
If most of your site should be private (for example a staff portal), Django 5.1 added LoginRequiredMiddleware. It makes every page require login, and you mark the public exceptions with the @login_not_required decorator.
Key points
include("django.contrib.auth.urls")adds login, logout and password views; you write the templates intemplates/registration/.- Log out with a POST form:
LogoutViewrejects GET requests since Django 5.0. - Build sign-up with
UserCreationFormand log the new user in withlogin(). - Protect views with
@login_requiredorLoginRequiredMixin; checkuser.is_authenticatedin templates.
Tip: use the ← and → keys to move between pages.
