Django Authentication
Almost every site needs users who can sign up, log in and log out, and pages only some people may see. django.contrib.auth provides all of it: a User model, secure password hashing, login/logout functions and views, permissions and groups, and decorators to protect views.
| Piece | What it gives you |
|---|---|
User model |
username, password (hashed), email, first_name, last_name, is_staff, is_superuser, is_active |
authenticate() / login() / logout() |
check credentials and manage the logged-in state in the session |
request.user |
the current user — or an AnonymousUser (added by AuthenticationMiddleware) |
@login_required, LoginRequiredMixin |
protect views |
| permissions & groups | user.has_perm("app.change_book") |
django.contrib.auth.urls |
ready-made login, logout and password-reset views |
Note: The examples below set
PASSWORD_HASHERSto the fast MD5 hasher so they run quickly in your browser. Never do that in a real project — Django's default (PBKDF2 with many iterations, or Argon2) is deliberately slow to resist password cracking.
Users and passwords
Create users with create_user(), which hashes the password. Never assign user.password = "..." directly — use set_password():
import django
from django.conf import settings
settings.configure(
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
PASSWORD_HASHERS=["django.contrib.auth.hashers.MD5PasswordHasher"], # demo only!
)
django.setup()
from django.core.management import call_command
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
call_command("migrate", verbosity=0)
user = User.objects.create_user("thao", email="thao@example.com", password="correct horse")
print(user.username, user.email, user.is_staff, user.is_superuser)
print("stored:", user.password.split("quot;)[0], "+ salt + hash (never the plain text)")
print(user.check_password("correct horse"), user.check_password("wrong"))
print(authenticate(username="thao", password="correct horse"))
print(authenticate(username="thao", password="nope"))
user.set_password("new pass 2026")
user.save()
print(authenticate(username="thao", password="new pass 2026") == user)
admin = User.objects.create_superuser("root", "root@example.com", "s3cret!")
print(admin.is_staff, admin.is_superuser)thao thao@example.com False False
stored: md5 + salt + hash (never the plain text)
True False
thao
None
True
True True
authenticate() returns the User when the credentials are right and None otherwise.
Logging in and out
A login view checks the credentials with authenticate() and then calls login(request, user), which stores the user's id in the session. On later requests, AuthenticationMiddleware loads that user into request.user:
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(
SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"],
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "django.contrib.sessions"],
MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
PASSWORD_HASHERS=["django.contrib.auth.hashers.MD5PasswordHasher"],
)
django.setup()
from django.core.management import call_command
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.urls import path
from django.test import Client
call_command("migrate", verbosity=0)
User.objects.create_user("thao", password="correct horse")
def login_view(request):
user = authenticate(request, username=request.POST["username"], password=request.POST["password"])
if user is None:
return HttpResponse("Invalid username or password", status=401)
login(request, user)
return HttpResponse(f"Welcome, {user.username}")
def logout_view(request):
logout(request)
return HttpResponse("Bye")
def whoami(request):
u = request.user
return HttpResponse(f"{u} (authenticated={u.is_authenticated})")
urls.urlpatterns = [path("login/", login_view), path("logout/", logout_view), path("me/", whoami)]
c = Client()
print(c.get("/me/").content.decode())
r = c.post("/login/", {"username": "thao", "password": "oops"})
print(r.status_code, r.content.decode())
print(c.post("/login/", {"username": "thao", "password": "correct horse"}).content.decode())
print(c.get("/me/").content.decode())
print(c.post("/logout/").content.decode())
print(c.get("/me/").content.decode())AnonymousUser (authenticated=False)
401 Invalid username or password
Welcome, thao
thao (authenticated=True)
Bye
AnonymousUser (authenticated=False)
In real projects you rarely write this view yourself: path("accounts/", include("django.contrib.auth.urls")) gives you LoginView, LogoutView and password-reset views; you only provide the templates (registration/login.html, …).
Protecting views
@login_required redirects anonymous visitors to settings.LOGIN_URL (default /accounts/login/) with a next parameter, so they return to the page after logging in. @permission_required and user.has_perm() check finer-grained permissions:
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(
SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"],
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "django.contrib.sessions"],
MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
PASSWORD_HASHERS=["django.contrib.auth.hashers.MD5PasswordHasher"],
)
django.setup()
from django.core.management import call_command
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.models import User, Permission
from django.http import HttpResponse
from django.urls import path
from django.test import Client
call_command("migrate", verbosity=0)
@login_required
def dashboard(request):
return HttpResponse(f"Dashboard of {request.user.username}")
@permission_required("auth.add_user", raise_exception=True)
def invite(request):
return HttpResponse("Invitation sent")
urls.urlpatterns = [path("dashboard/", dashboard), path("invite/", invite)]
member = User.objects.create_user("member", password="pw")
manager = User.objects.create_user("manager", password="pw")
manager.user_permissions.add(Permission.objects.get(codename="add_user"))
c = Client()
r = c.get("/dashboard/")
print("anonymous:", r.status_code, r["Location"])
c.force_login(member) # test helper: log in without a password check
print("member: ", c.get("/dashboard/").content.decode(), "|", c.get("/invite/").status_code)
c.force_login(manager)
print("manager: ", c.get("/invite/").content.decode())
print(User.objects.get(username="manager").has_perm("auth.add_user"))anonymous: 302 /accounts/login/?next=/dashboard/
member: Dashboard of member | 403
manager: Invitation sent
True
For class-based views use LoginRequiredMixin and PermissionRequiredMixin (placed first in the base classes).
Users in templates
With the auth context processor enabled, every template has user and perms:
{% if user.is_authenticated %}
Hi {{ user.first_name|default:user.username }}! <form method="post" action="{% url 'logout' %}">{% csrf_token %}<button>Log out</button></form>
{% else %}
<a href="{% url 'login' %}?next={{ request.path }}">Log in</a>
{% endif %}
{% if perms.books.add_book %}<a href="{% url 'book_create' %}">Add book</a>{% endif %}Tip: Starting a new project? Define a custom user model (
class User(AbstractUser): passandAUTH_USER_MODEL = "accounts.User") before the first migration. Switching later is painful, and it lets you add fields such asphoneeasily. Refer to the user model withsettings.AUTH_USER_MODELorget_user_model().
Test yourself
What does authenticate() return when the password is wrong?
- False
- An AnonymousUser
- None
- It raises an exception
What does @login_required do for an anonymous visitor?
- Returns 404
- Redirects to LOGIN_URL with a
nextparameter - Shows a blank page
- Logs them in automatically
How should you change a user's password?
- user.password = "new"
- user.set_password("new") then save()
- User.objects.update(password="new")
- user.change("new")