0
0
Djangoframework~10 mins

Built-in middleware overview in Django - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Built-in middleware overview
Request arrives
Process Request Middleware 1
Process Request Middleware 2
View function executes
Process Response Middleware N
Process Response Middleware N-1
Response sent back to client
Middleware in Django wraps around requests and responses, processing them in order before and after the view runs.
Execution Sample
Django
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',
]
This list shows Django's default built-in middleware that process requests and responses in order.
Execution Table
StepMiddleware PhaseMiddleware NameActionEffect
1Process RequestSecurityMiddlewareCheck security headersAdds security headers if missing
2Process RequestSessionMiddlewareLoad session dataAttaches session info to request
3Process RequestCommonMiddlewareHandle URL normalizationRedirects or modifies URL if needed
4Process RequestCsrfViewMiddlewareCheck CSRF tokenBlocks request if token invalid
5Process RequestAuthenticationMiddlewareAttach user infoAdds user object to request
6Process RequestMessageMiddlewarePrepare messagesEnables message framework
7Process RequestXFrameOptionsMiddlewareSet X-Frame-Options headerPrevents clickjacking
8View ExecutionView FunctionProcess request dataGenerates response
9Process ResponseXFrameOptionsMiddlewareAdd headers to responseSets X-Frame-Options header
10Process ResponseMessageMiddlewareAdd messages to responseIncludes messages in response
11Process ResponseAuthenticationMiddlewareClean upFinalizes user state
12Process ResponseCsrfViewMiddlewareAdd CSRF cookieSets CSRF cookie in response
13Process ResponseCommonMiddlewareModify responseApplies content transformations
14Process ResponseSessionMiddlewareSave session dataSaves session changes
15Process ResponseSecurityMiddlewareAdd security headersEnsures security headers present
16Response SentClientReceive responsePage or data shown to user
💡 All middleware processed request and response in order; response sent to client.
Variable Tracker
VariableStartAfter SecurityMiddlewareAfter SessionMiddlewareAfter CommonMiddlewareAfter CsrfViewMiddlewareAfter AuthenticationMiddlewareAfter MessageMiddlewareAfter XFrameOptionsMiddlewareAfter ViewFinal
request.headersInitial headersSecurity headers addedSession cookie loadedURL normalizedCSRF token checkedUser info attachedMessages preparedX-Frame-Options header setView processes requestFinal headers with security and session
request.sessionEmptyEmptyLoaded session dataLoaded session dataLoaded session dataLoaded session dataLoaded session dataLoaded session dataUsed by viewSaved session data
request.userAnonymousAnonymousAnonymousAnonymousUser attachedUser attachedUser attachedUser attachedUsed by viewUser finalized
response.headersNoneNoneNoneNoneNoneNoneNoneNoneCreated by viewSecurity and X-Frame headers added
Key Moments - 3 Insights
Why does middleware process requests in one order but responses in reverse?
Middleware wraps around the view like layers. Requests go in order to prepare data; responses go back through middleware in reverse to finalize or modify before sending. See execution_table steps 1-7 for request and 9-15 for response.
What happens if CsrfViewMiddleware blocks a request?
If CSRF token is invalid, CsrfViewMiddleware stops the request before the view runs (step 4). No further middleware or view executes, and an error response is sent.
How does SessionMiddleware affect request and response?
SessionMiddleware loads session data into request before the view (step 2) and saves any changes to session after the response (step 14). This keeps user session consistent.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what middleware attaches user info to the request?
AAuthenticationMiddleware
BSessionMiddleware
CCsrfViewMiddleware
DCommonMiddleware
💡 Hint
Check step 5 in the execution_table where user info is attached.
At which step does the CSRF token get checked during request processing?
AStep 3
BStep 6
CStep 4
DStep 10
💡 Hint
Look at the execution_table under Process Request phase for CSRF token check.
If SessionMiddleware did not save session data after response, what would happen?
AUser info would not be attached
BSession data would not persist between requests
CCSRF token would be invalid
DSecurity headers would be missing
💡 Hint
Refer to variable_tracker row for request.session and step 14 in execution_table.
Concept Snapshot
Django built-in middleware are layers that process requests before the view and responses after.
They run in order on request, reverse on response.
Common middleware include Security, Session, CSRF, Authentication, and Message.
They add security headers, manage sessions, check CSRF tokens, attach user info, and handle messages.
Middleware must be ordered correctly in settings for proper behavior.
Full Transcript
Django's built-in middleware work like layers wrapping around your view. When a request comes in, it passes through each middleware in the order listed, allowing each to check or modify the request. For example, SecurityMiddleware adds security headers, SessionMiddleware loads session data, and CsrfViewMiddleware checks the CSRF token. If any middleware blocks the request, the view does not run. After the view creates a response, the response passes back through the middleware in reverse order. This lets middleware add headers or save session data before the response goes to the client. Understanding this flow helps you see how Django manages security, sessions, authentication, and messages automatically.