How a Request and a Login Flow Through Django: URLconf, ORM, CSRF, Password Hashes and Sessions
Follow the home page from URLconf to SQLite and back (8 queries), then a login: the csrftoken, a 403 without it, the pbkdf2 password hash, the django_session row, the sessionid cookie, and a review finding about who may write posts.
What you will learn
- Trace one GET from the URLconf through the view, the ORM and the template, and count its queries
- Explain how the CSRF token in a form and a cookie blocks forged POSTs
- Describe what Django stores for a password and what login() writes to django_session
- Show why login_required and a hidden button are not a permission check, and where the check belongs
Before you start
- Django views, URLs and templates
- Python decorators
- HTTP cookies and status codes
Knowing the files of a Django app tells you what's there. Knowing the flow tells you what runs, and in which order. That's what you need when you review code an AI tool wrote. In this article we follow one request through the finished blog, from the browser to the database and back, and then follow a login: what really happens when you type a password and press the button. Nothing new gets built.
Think of a restaurant kitchen. An order slip comes in, someone at the pass reads it and sends it to the right cook, the cook takes what's needed from the pantry, and the dish is plated and goes out. In Django, the slip is the URL, the pass is the URLconf, the cook is the view, the pantry is the database behind the ORM, and the plating is the template. For a regular customer, the kitchen keeps a ticket with their table number, so it knows who they are on every order. That ticket is the session cookie.
One GET, end to end
The URLconf picks the view
In blogproject/urls.py, the empty path is handed on with include to blog.urls, where each path names a view. Asking Django's resolve() where four addresses go:
/ -> blog.views.home kwargs={} name=home
/login/ -> blog.views.login_view kwargs={} name=login
/post/create/ -> blog.views.create_post kwargs={} name=create_post
/post/getting-started-with-machine-learning/ -> blog.views.post_detail kwargs={'slug': 'getting-started-with-machine-learning'} name=post_detail
For a post's own page, the slug part of the path is cut out and passed to post_detail as a keyword argument. The URLconf is only a lookup table; it runs no logic of its own.
The view asks the ORM
The home view starts with Post.objects.filter(status='published'). That line doesn't touch the database. It's a query waiting to run. The Paginator wants six posts per page, so first it counts, then it fetches one page:
SELECT COUNT(*) AS "__count" FROM "blog_post" WHERE "blog_post"."status" = 'published'
SELECT "blog_post"."id", "blog_post"."title", "blog_post"."slug", ... LIMIT 6
Six rows come back, each becomes a Post object, and render puts them in the context under the name posts.
The template builds the page, and a hidden cost
render uses home.html, which extends base.html. The test client recorded:
status 200
content-type text/html; charset=utf-8
templates ['blog/home.html', 'blog/base.html']
queries 8
Why eight? The loop prints post.author.username for each post, and each of those asks the database for the user again. Two queries are for the posts and six are the same SELECT ... FROM "auth_user" for the same author. This is the classic N+1 pattern. Django's fix is select_related, and it's a good thing to ask your AI agent about in review.
The login page hands out a token
Now the login. The browser first asks for GET /login/. In login.html, the form has method POST, and right under it is the CSRF tag:
<form method="POST">
{% csrf_token %}
The run measured what came back:
status 200
cookie names ['csrftoken']
csrftoken cookie length 32
hidden field csrfmiddlewaretoken present True
hidden field length 64
The tag puts a hidden field, csrfmiddlewaretoken, in the form, and the response sets a cookie called csrftoken. The browser now holds the secret twice. Another website can make your browser send a request, but it can't read this form, so it can't copy the hidden field. That's the whole trick.
A POST without the token
Before any view runs, every request passes the middleware list in settings.py:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
Three matter for a login. SessionMiddleware loads the session, CsrfViewMiddleware checks the token on every POST, and AuthenticationMiddleware works out who the user is. A POST to /login/ without the token:
status 403
sessionid cookie set False
The CSRF check stops it. The login view never runs and no session cookie is set. The running server gave the same 403, so it isn't only a test client thing.
Checking the password
Now the proper POST, with the token, a username and a password. The CSRF check passes, so login_view runs:
def login_view(request):
"""User login view"""
if request.user.is_authenticated:
return redirect('home')
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
messages.success(request, f'Welcome back, {username}!')
next_url = request.GET.get('next', 'home')
return redirect(next_url)
else:
messages.error(request, 'Invalid username or password.')
return render(request, 'blog/login.html')
authenticate runs one query: select from auth_user where the username matches. Then look at the password column. Django never stores your password, only a hash of it. The run took the stored value apart:
algorithm pbkdf2_sha256
iterations 1500000
salt length 22
hash length 44
plain password stored: False
The four parts are the algorithm, the iteration count (1,500,000), a salt and the hash itself. Django hashes the password you typed with the same salt and iterations and compares the two results. If they match, authenticate returns the user.
A session row and a cookie
login(request, user) starts the session. Django makes a new 32-character session key and inserts a row into django_session (key and data cut short here):
INSERT INTO "django_session" ("session_key", "session_data", "expire_date") VALUES ('...', '...', '2026-11-23 00:50:06.401322')
UPDATE "auth_user" SET "last_login" = '2026-11-09 00:50:06.414844' WHERE "auth_user"."id" = 2
The expire date is two weeks away. Decoded, the session data holds three keys, _auth_user_backend, _auth_user_hash and _auth_user_id, and _auth_user_id is 2, the user who logged in. Django also updates last_login. The response:
status 302
redirect to /
cookie names ['csrftoken', 'messages', 'sessionid']
sessionid length 32
A 302 redirect to the home page, a sessionid cookie with that same key, and a messages cookie for the welcome note.
The next request carries the cookie
The browser asks for /dashboard/ and sends the sessionid cookie along. The dashboard came back with status 200 and four queries:
SELECT "django_session"."session_key", "django_session"."session_data", "django_session"."expire_date" FROM "django_session" WHERE ("django_session"."expire_date" > '...' AND "django_session"."session_key" = '...') LIMIT 21
SELECT "auth_user"."id", ... FROM "auth_user" WHERE "auth_user"."id" = 2 LIMIT 21
SELECT COUNT(*) AS "__count" FROM "blog_post" WHERE "blog_post"."author_id" = 2
SELECT "blog_post"."id", "blog_post"."title", ...
SessionMiddleware looks up the key, but only if the row hasn't expired. AuthenticationMiddleware loads user 2 into request.user. The dashboard has @login_required, which checks request.user and passes. Then the view fetches only that author's posts. The first two queries just work out who you are, and that happens on every request. That's why you stay logged in from page to page.
login_required on the write view
@login_required
def create_post(request):
"""Create a new blog post"""
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.save()
messages.success(request, 'Post created successfully!')
return redirect('dashboard')
else:
form = PostForm()
return render(request, 'blog/post_form.html', {'form': form, 'title': 'Create New Post'})
An anonymous browser, with no cookie:
GET status 302 -> /login/?next=/post/create/
POST status 302 -> /login/?next=/post/create/
The view never runs. Both GET and POST are redirected to the login page with next set. The /login/ address comes from LOGIN_URL = 'login' in settings, and after you log in, login_view reads next and takes you back.
Who is allowed to write?
Here's a question for review. In base.html, the Create Post link only shows for staff:
{% if user.is_staff %}
<a href="{% url 'create_post' %}" ...>Create Post</a>
{% endif %}
The lecture logged in as a seeded user who is not staff (is_staff False), so that user never sees the button. But the URL is still there. A direct POST to /post/create/:
is_staff False
status 302 -> /dashboard/
posts before 6, after 7
The post was created. Hiding a button in a template isn't a check. The view only has login_required, so any logged-in user can post. That's a review finding.
The check belongs in the view
Here's a sketch from the lecture, not code in the blog, of a decorator that puts the check where it belongs:
def staff_required(view):
def wrapper(request, *a, **k):
if not request.user.is_staff:
raise PermissionDenied
return view(request, *a, **k)
return wrapper
@login_required
@staff_required
def create_post_sketch(request):
return HttpResponse('ok')
If request.user.is_staff is False, it raises PermissionDenied, and Django turns that into 403. Stacked under login_required, you must first be logged in and then be staff. In the run, the non-staff user got 403 and the staff user got 200.
You could ask an AI agent for this change with a prompt like: Role: you are a Django reviewer. Context: the blog's create, edit and delete views use only login_required. Task: add a staff check in the views, keep the template check. Format: a diff and one test per view. Then review the diff. Keep the button hidden for a cleaner page, but the real check lives in the view.
Common mistakes
- Treating a hidden link as security. Anyone can type the URL or send the POST.
- Switching the CSRF check off to "fix" a 403. A 403 on a form POST usually means the form has no
{% csrf_token %}. Add the token; the check is the protection working. - Assuming
login_requiredchecks roles. It only checks that someone is logged in. - Missing N+1 queries in a template loop. Count the queries;
select_relatedfetches the author with the post.
Quick recap
| Piece | What it does | Seen in the run |
|---|---|---|
| URLconf | picks the view | / goes to blog.views.home |
| ORM | writes the SQL | COUNT, then LIMIT 6; 8 queries on the home page |
csrftoken | proves the form came from the site | no token, 403 |
| Password | checked as a hash | pbkdf2_sha256, 1,500,000 iterations |
sessionid | carried on every request | row in django_session, _auth_user_id 2 |
login_required | logged in or redirected | 302 to /login/?next=/post/create/ |
To check these flows with automated tests instead of by hand, see testing the Django blog with pytest.
Try it yourself
Log in to your blog, open the browser's developer tools, find the sessionid cookie, and then find the same key in the django_session table.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
One small project lists two blog posts three times: as a Django view, a Flask route and a FastAPI endpoint. See each shape with its real output, what each framework includes, and a three-question way to choose.
Getting Started with Django: Models, Views, Templates, the ORM and the Admin
A tiny Django menu app with one model, one view, one URL, one template and the admin. What each file does, how one request travels through them, and the real output of a run.
Your First Django Project and App: uv, startproject, startapp and a First View
Set up a Django project called blogproject with uv, add an app called blog, write one view that returns Hello blog, give it the empty path and run the server. Every command with its real output.
The Django Project Folder Structure, File by File: Reading a Blog an AI Agent Built
A tour of a finished Django blog: manage.py, the project package, the blog app with its models, views, templates, forms and admin, a custom command, the REST API and Swagger docs, plus the review points check --deploy found.
