Full answer
Django's auth system answers two questions: who are you (authentication) and what may you do (authorisation, through permissions and groups).
Main parts:
Usermodel withusername,password(a hash, never plain text),email,is_active,is_staff,is_superuser.- Password hashing with PBKDF2 by default; Argon2 and bcrypt are available.
user.set_password()hashes;user.check_password()verifies. AuthenticationMiddlewareputsrequest.useron every request. Anonymous visitors get anAnonymousUser.- Sessions (
SessionMiddleware) remember the logged-in user between requests through a cookie that holds only a session key.
The login steps:
user = authenticate(request, username=..., password=...)asks each backend inAUTHENTICATION_BACKENDS. It returns the user, orNoneif the details are wrong or the user is inactive.login(request, user)saves the user ID in the session and rotates the session key, which prevents session fixation.logout(request)flushes the session.
Protecting views:
@login_requiredfor function views,LoginRequiredMixinfor class views. Anonymous users are redirected tosettings.LOGIN_URLwith?next=/original/path/.@permission_required("library.add_book")oruser.has_perm()for permissions.- Django 5.1 added
LoginRequiredMiddleware, which protects every view by default; mark public ones with@login_not_required.
Django also ships ready views: LoginView, LogoutView (POST only since Django 5.0), and the password reset and change views.
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "django.contrib.sessions", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.contrib.auth import authenticate, get_user_model, login
from django.contrib.auth.decorators import login_required
from django.core.management import call_command
from django.http import HttpResponse
from django.test import Client
from django.urls import path
settings.MIDDLEWARE = [
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
]
settings.ROOT_URLCONF = __name__
settings.LOGIN_URL = "/login/"
settings.PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"] # fast, for this demo only
call_command("migrate", verbosity=0)
User = get_user_model()
User.objects.create_user("priya", password="Chai-at-4pm")
@login_required
def my_marks(request):
return HttpResponse(f"Marks for {request.user.username}")
def login_view(request):
user = authenticate(request, username=request.POST["u"], password=request.POST["p"])
if user is None:
return HttpResponse("wrong details", status=401)
login(request, user)
return HttpResponse("logged in")
urlpatterns = [path("marks/", my_marks), path("login/", login_view)]
c = Client()
r = c.get("/marks/")
print(r.status_code, r["Location"])
print(c.post("/login/", {"u": "priya", "p": "wrong"}).status_code)
print(c.post("/login/", {"u": "priya", "p": "Chai-at-4pm"}).content.decode())
print(c.get("/marks/").content.decode())
print(User.objects.get(username="priya").password.split("$")[0])
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. MD5 hashing is used only to make the demo fast; keep the default hashers in real projects. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): 302 /login/?next=/marks/ 401 logged in Marks for priya md5
Key points
- Passwords are stored as salted hashes
- authenticate() checks; login() starts the session
- request.user comes from AuthenticationMiddleware
- login_required redirects to LOGIN_URL with ?next=
- Django 5.1 adds LoginRequiredMiddleware
Common mistakes
- Storing or comparing plain-text passwords
- Calling login() without authenticate() first
- Checking request.user.is_authenticated in templates but not protecting the view
- Using a GET link for logout (Django 5.0 LogoutView requires POST)
Follow-ups
- How would you let users log in with email instead of username?
- What is session fixation and how does login() prevent it?
- How do groups and permissions work together?
Tips
- Separate authentication from authorisation in your answer
- Mention password hashing and set_password()
- Note the Django 5.x changes: POST-only logout and LoginRequiredMiddleware