Bird
Raised Fist0
Djangoframework~10 mins

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

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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.

Practice

(1/5)
1. Which of the following is a primary purpose of Django's built-in middleware?
easy
A. To automatically process requests and responses
B. To create database models
C. To write HTML templates
D. To manage static files

Solution

  1. Step 1: Understand middleware role

    Django middleware acts as a layer that processes requests before views and responses after views.
  2. Step 2: Identify correct purpose

    Creating models, writing templates, and managing static files are handled by other parts of Django, not middleware.
  3. Final Answer:

    To automatically process requests and responses -> Option A
  4. Quick Check:

    Middleware = process requests/responses [OK]
Hint: Middleware handles request/response flow automatically [OK]
Common Mistakes:
  • Confusing middleware with models or templates
  • Thinking middleware manages static files
  • Assuming middleware writes HTML
2. Which of the following is the correct way to add built-in middleware in Django's settings.py?
easy
A. MIDDLEWARE = django.middleware.security.SecurityMiddleware
B. MIDDLEWARE = {'django.middleware.security.SecurityMiddleware'}
C. MIDDLEWARE = ('django.middleware.security.SecurityMiddleware')
D. MIDDLEWARE = ['django.middleware.security.SecurityMiddleware']

Solution

  1. Step 1: Check correct data type for MIDDLEWARE

    Django expects MIDDLEWARE to be a list of strings representing middleware classes.
  2. Step 2: Identify correct syntax

    MIDDLEWARE = ['django.middleware.security.SecurityMiddleware'] uses a list with one string, which is correct. Options B uses a set, C is a string without list, and D is invalid syntax.
  3. Final Answer:

    MIDDLEWARE = ['django.middleware.security.SecurityMiddleware'] -> Option D
  4. Quick Check:

    Middleware list syntax = MIDDLEWARE = ['django.middleware.security.SecurityMiddleware'] [OK]
Hint: Middleware must be a list of strings in settings.py [OK]
Common Mistakes:
  • Using sets or tuples instead of lists
  • Omitting quotes around middleware path
  • Assigning middleware without brackets
3. Given this middleware order in settings.py:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
]

What happens if a request triggers a CSRF failure?
medium
A. The request passes through all middleware without blocking
B. The session middleware blocks the request before CSRF check
C. The CSRF middleware blocks the request before reaching the view
D. The security middleware blocks the request after CSRF check

Solution

  1. Step 1: Understand middleware order and function

    Middleware runs in order on request. CSRF middleware checks tokens and blocks if invalid.
  2. Step 2: Identify which middleware blocks on CSRF failure

    CSRF middleware is responsible for blocking bad requests before views. Session middleware runs earlier but doesn't block CSRF. Security middleware runs first but does not handle CSRF.
  3. Final Answer:

    The CSRF middleware blocks the request before reaching the view -> Option C
  4. Quick Check:

    CSRF middleware blocks bad requests [OK]
Hint: CSRF middleware blocks invalid tokens before views [OK]
Common Mistakes:
  • Thinking session middleware blocks CSRF errors
  • Assuming security middleware handles CSRF
  • Believing request always passes through
4. You added 'django.middleware.csrf.CsrfViewMiddleware' after 'django.middleware.security.SecurityMiddleware' but get CSRF errors on valid requests. What is the likely problem?
medium
A. Security middleware must be removed to fix CSRF errors
B. Middleware order is incorrect; CSRF middleware should come after session middleware
C. CSRF middleware requires no session middleware to work
D. CSRF middleware should be first in the list

Solution

  1. Step 1: Recall middleware order importance

    CSRF middleware depends on session middleware to access session data for tokens.
  2. Step 2: Identify correct order

    Session middleware must come before CSRF middleware. If CSRF middleware is before session, it can't validate tokens properly, causing errors.
  3. Final Answer:

    Middleware order is incorrect; CSRF middleware should come after session middleware -> Option B
  4. Quick Check:

    Session before CSRF middleware fixes errors [OK]
Hint: Session middleware must precede CSRF middleware [OK]
Common Mistakes:
  • Removing security middleware unnecessarily
  • Placing CSRF middleware first
  • Ignoring middleware order dependencies
5. You want to add a custom middleware that logs request info and must run after security checks but before session handling. Given the default order:
[
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
]

Where should you insert your custom middleware?
hard
A. Between SecurityMiddleware and SessionMiddleware
B. Before SecurityMiddleware
C. After SessionMiddleware
D. At the end of the list

Solution

  1. Step 1: Understand middleware order effect

    Middleware runs top to bottom on request. To run after security but before session, place custom middleware between them.
  2. Step 2: Identify correct insertion point

    SecurityMiddleware is first, SessionMiddleware second. Insert custom middleware as second item to run after security and before session.
  3. Final Answer:

    Between SecurityMiddleware and SessionMiddleware -> Option A
  4. Quick Check:

    Insert custom middleware between security and session [OK]
Hint: Middleware order controls execution sequence [OK]
Common Mistakes:
  • Placing custom middleware before security
  • Putting it after session middleware
  • Adding it at the end ignoring order