Chapter 12 · 10 min read
User Authentication
User Authentication
Almost every site needs accounts. Django ships with a complete authentication system: users, hashed passwords, sessions, permissions, and ready-made views for login and logout. In this chapter you will add sign-up, login and logout to the blog and protect pages from anonymous visitors.
What you will learn
- How Django knows who the current visitor is.
- How to use the built-in login and logout views.
- How to build a sign-up page with
UserCreationForm. - How to change the navigation for logged-in users.
- How to protect views.
How it works
django.contrib.authstores users and passwords. Passwords are never saved as plain text; they are hashed with a slow, salted algorithm. Django 6.1 raised the default iteration count of the PBKDF2 hasher to 1,500,000 to keep guessing slow.django.contrib.sessionsremembers a visitor between requests using a cookie.- Middleware attaches the current user to every request as
request.user. Templates receive it asuser. user.is_authenticatedisTruefor logged-in users. Anonymous visitors get anAnonymousUserobject.
The module django.contrib.auth.urls provides these URLs, which you include under a prefix of your choice:
| Address | Name | Purpose |
|---|---|---|
login/ | login | Log in form |
logout/ | logout | Log out (POST only) |
password_change/ | password_change | Change password |
password_reset/ | password_reset | Start a password reset |
You only supply templates. Sign-up is not included, so you write a small view for it.
Step by step
1. The sign-up view
Add these imports at the top of blog/views.py:
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
and this class at the bottom:
class SignUpView(CreateView):
form_class = UserCreationForm
template_name = "registration/signup.html"
success_url = reverse_lazy("login")
UserCreationForm is a built-in form with username and two password fields, including password validation. The generic CreateView saves the new user and then redirects to the URL named login.
2. The URLs
Replace config/urls.py:
from django.contrib import admin
from django.urls import include, path
from blog.views import SignUpView
urlpatterns = [
path("admin/", admin.site.urls),
path("accounts/signup/", SignUpView.as_view(), name="signup"),
path("accounts/", include("django.contrib.auth.urls")),
path("", include("blog.urls")),
]
3. Settings
Add to the bottom of config/settings.py:
LOGIN_REDIRECT_URL = "blog:home"
LOGOUT_REDIRECT_URL = "blog:home"
Without LOGIN_REDIRECT_URL, Django sends users to /accounts/profile/ after login, which does not exist and gives a 404.
4. The templates
The built-in views look for templates in a registration folder. Create blog/templates/registration/login.html:
{% extends "blog/base.html" %}
{% block content %}
<h1>Log in</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Log in</button>
</form>
<p>New here? <a href="{% url 'signup' %}">Create an account</a>.</p>
{% endblock %}
and blog/templates/registration/signup.html:
{% extends "blog/base.html" %}
{% block content %}
<h1>Sign up</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Create account</button>
</form>
{% endblock %}
5. Navigation that reacts to login state
Replace blog/templates/blog/base.html:
{% load static %}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{% block title %}My Blog{% endblock %}</title>
<link rel="stylesheet" href="{% static 'blog/style.css' %}">
</head>
<body>
<nav>
<a href="{% url 'blog:home' %}">Home</a>
{% if user.is_authenticated %}
<a href="{% url 'blog:create' %}">New post</a>
<span>Hi, {{ user.username }}</span>
<form method="post" action="{% url 'logout' %}" class="inline">
{% 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 %}
</nav>
<main>{% block content %}{% endblock %}</main>
</body>
</html>
Logging out is a small POST form, not a link. Since Django 5.0 the logout view accepts only POST, so that a malicious page cannot log you out by loading an image.
Protecting views
| Where | Tool |
|---|---|
| Function view | @login_required decorator |
| Class view | LoginRequiredMixin |
| Extra rule such as "must be the author" | UserPassesTestMixin |
| Template | {% if user.is_authenticated %} |
login_required sends anonymous visitors to the login page with a next parameter so they return afterwards, for example /accounts/login/?next=/post/new/. The default login page is set with LOGIN_URL, which already defaults to /accounts/login/.
Email in development
A new Django 6.1 project's generated settings include a MAILERS setting that sends email to the terminal. That is useful here: if you try the password reset page, the email text appears in your terminal window. Before you deploy you must replace it with a real email backend, which the deployment chapter covers.
Permissions and custom user models
Django also has permissions and groups for finer rules. For a real application, decide whether you need a custom user model before you create your first migration, because changing it later is hard. For learning, the default user is fine.
Check it works
- Open
/accounts/signup/, create a user, and you land on the login page. - After logging in the navigation shows
Hi, yournameand a Log out button. - Click Log out, then open
/post/new/: you are sent to/accounts/login/?next=/post/new/.
Exercises with solutions
Exercise 1: author pages
Create /author/<username>/ listing that author's published posts.
Solution.
class AuthorPostsView(ListView):
model = Post
template_name = "blog/post_list.html"
def get_queryset(self):
return Post.objects.filter(
published=True, author__username=self.kwargs["username"]
).select_related("author")
path("author/<str:username>/", views.AuthorPostsView.as_view(), name="author"),
In post_list.html link the author's name: <a href="{% url 'blog:author' post.author.username %}">{{ post.author.username }}</a>.
Exercise 2: a friendly message
Show "Log in to write posts." to anonymous visitors on the home page.
Solution. In post_list.html, under the heading:
{% if not user.is_authenticated %}
<p>Log in to write posts.</p>
{% endif %}
Exercise 3: where do you land?
Make users return to the page they wanted after logging in.
Solution. Nothing needs changing: the built-in login view reads the next parameter that login_required and LoginRequiredMixin add. Test it by logging out and opening /post/new/; after logging in you arrive at /post/new/, not at the home page. (LOGIN_REDIRECT_URL is only used when there is no next.)
Common mistakes
- Logging out with a plain link. The request is a GET, so Django answers 405. Use a POST form with
{% csrf_token %}. - Putting
login.htmlin the wrong folder. It must be atregistration/login.htmlinside a templates folder. - Missing
LOGIN_REDIRECT_URL. After login Django sends you to/accounts/profile/, which gives a 404. - Confusing the admin login with the site login. They share a session, but are different pages.
- Weak passwords rejected. Django's validators block very common or numeric-only passwords. Use a longer one.
- Starting a serious project on the default user model without thinking. Decide on a custom user model early.
Key takeaways
django.contrib.auth.urlsgives you login, logout and password views; you write templates.- Sign-up needs a small view around
UserCreationForm. request.userand the template variableuseridentify the visitor.- Logout is POST-only.
- Protect views with
login_requiredorLoginRequiredMixin.
Official links
- Authentication system: https://docs.djangoproject.com/en/6.1/topics/auth/
- Using the authentication system: https://docs.djangoproject.com/en/6.1/topics/auth/default/
