Full answer
Steps for one request:
- The server (Gunicorn, Uvicorn, runserver) calls Django's WSGI or ASGI handler.
- The handler creates an
HttpRequestwith method, headers, GET, POST and body. - Each middleware in
MIDDLEWAREruns top to bottom (its code beforeget_response). Security, sessions, CSRF and authentication middleware attach data such asrequest.sessionandrequest.user. - The URL resolver matches
request.path_infoagainstROOT_URLCONF, and finds a view plus its arguments. No match raisesHttp404. process_viewhooks of middleware run, then the view runs. The view reads data (ORM), makes decisions and returns anHttpResponse,JsonResponse, redirect or aTemplateResponse.- Template rendering happens (lazily for
TemplateResponse). - The response goes back up through the middleware bottom to top (code after
get_response), where headers, cookies and compression are added. - The handler sends the response. Exceptions are converted into 404, 403, 500 responses by the handler or error views;
process_exceptionhooks run first.
Order matters. SessionMiddleware must come before AuthenticationMiddleware, because the user is read from the session. A middleware that returns early (like a maintenance page) short-circuits everything below it.
Signals such as request_started and request_finished fire at the edges of this flow, and database connections are closed when the request ends.
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
ROOT_URLCONF=__name__,
MIDDLEWARE=["__main__.TraceOne", "__main__.TraceTwo"],
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.http import HttpResponse
from django.test import Client
from django.urls import path
events = []
class TraceOne:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
events.append("one: before view")
response = self.get_response(request)
events.append("one: after view")
return response
class TraceTwo:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
events.append("two: before view")
response = self.get_response(request)
events.append("two: after view")
return response
def process_view(self, request, view_func, view_args, view_kwargs):
events.append(f"two: process_view -> {view_func.__name__}")
def hello(request):
events.append("view runs")
return HttpResponse("hello")
urlpatterns = [path("hello/", hello)]
r = Client().get("/hello/")
print(r.status_code, r.content)
print("\n".join(events))
events.clear()
print(Client().get("/missing/").status_code, events)
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. The middleware classes live in the same file, referenced through the __main__ module path. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): 200 b'hello' one: before view two: before view two: process_view -> hello view runs two: after view one: after view 404 ['one: before view', 'two: before view', 'two: after view', 'one: after view']
Key points
- Server calls WSGI or ASGI handler, which builds HttpRequest
- Middleware runs in order down, then in reverse on the way back
- URLconf resolves the view; no match gives 404
- The view returns a response object
- Middleware order is a dependency order
Common mistakes
- Putting AuthenticationMiddleware before SessionMiddleware
- Assuming the view is the only code that touches the request
- Putting heavy work in middleware that runs on every request
- Forgetting that exceptions are turned into responses by the handler
Follow-ups
- What is the difference between process_view and the __call__ style?
- Where does CSRF checking happen?
- What changes in the flow under ASGI?
Tips
- Walk through the steps in order
- Mention reverse order for responses
- Name one order dependency