Django Middleware β The Onion Structure Wrapping Requests/Responses
Why MIDDLEWARE order matters and how chaining works internally
Requests enter: Security β Session β Common β Auth β View
Responses exit: View β Auth β Common β Session β Security
Like peeling an onion going in, wrapping it back going out.
Internal Implementation
get_response is the next link in the chain. Django iterates MIDDLEWARE list in reverse at startup, connecting each middleware's get_response to the next.
Why Order Matters
SessionMiddleware must precede AuthenticationMiddleware β Auth reads user info from session. Swap them and request.user is always Anonymous.
Key Points
MIDDLEWARE list order = request processing order (chained in reverse)
get_response(request) call executes next middleware/View
Request: outsideβin, Response: insideβout (onion structure)
Session must come before Auth for request.user to work