Django Middleware
Middleware is code that runs on every request and response, wrapped around your views like the layers of an onion. Each layer can inspect or modify the request on the way in, short-circuit with its own response, and inspect or modify the response on the way out. Sessions, authentication, CSRF protection and security headers are all implemented as middleware.
request ─▶ SecurityMiddleware ─▶ SessionMiddleware ─▶ ... ─▶ view
│
response ◀─ SecurityMiddleware ◀─ SessionMiddleware ◀─ ... ◀──┘The MIDDLEWARE setting lists the layers from outermost to innermost. A new project contains:
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware", # HTTPS redirects, security headers
"django.contrib.sessions.middleware.SessionMiddleware", # request.session
"django.middleware.common.CommonMiddleware", # APPEND_SLASH, etc.
"django.middleware.csrf.CsrfViewMiddleware", # CSRF protection
"django.contrib.auth.middleware.AuthenticationMiddleware",# request.user (needs sessions)
"django.contrib.messages.middleware.MessageMiddleware", # messages
"django.middleware.clickjacking.XFrameOptionsMiddleware", # X-Frame-Options header
]Order matters: AuthenticationMiddleware reads the session, so it must come after SessionMiddleware.
Writing middleware
A middleware is a factory: a callable that receives get_response (the next layer) once at start-up and returns a callable that handles each request. A function-based version:
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"],
MIDDLEWARE=["urls.timing_middleware"])
django.setup()
from django.http import HttpResponse
from django.urls import path
from django.test import Client
def timing_middleware(get_response):
print("middleware created once")
def middleware(request):
print(" before view:", request.path) # on the way in
response = get_response(request) # call the next layer / the view
response["X-Handled-By"] = "timing_middleware" # on the way out
print(" after view: ", response.status_code)
return response
return middleware
urls.timing_middleware = timing_middleware # make it importable as "urls.timing_middleware"
def hello(request):
print(" in the view")
return HttpResponse("hi")
urls.urlpatterns = [path("hello/", hello)]
c = Client()
r = c.get("/hello/")
print(r["X-Handled-By"])
c.get("/missing/")middleware created once
before view: /hello/
in the view
after view: 200
timing_middleware
before view: /missing/
after view: 404
In a project the function would live in a file such as core/middleware.py and be listed as "core.middleware.timing_middleware". Here the playground's urls module doubles as that file.
Class-based middleware and the onion order
Middleware is often written as a class: __init__ receives get_response, __call__ handles each request. With two layers you can see the onion: requests travel down the list, responses travel back up:
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"],
MIDDLEWARE=["urls.Outer", "urls.Inner"])
django.setup()
from django.http import HttpResponse
from django.urls import path
from django.test import Client
class Layer:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
print(f"{type(self).__name__}: request in")
response = self.get_response(request)
print(f"{type(self).__name__}: response out")
return response
class Outer(Layer):
pass
class Inner(Layer):
pass
urls.Outer, urls.Inner = Outer, Inner
def view(request):
print("view")
return HttpResponse("ok")
urls.urlpatterns = [path("", view)]
Client().get("/")Outer: request in
Inner: request in
view
Inner: response out
Outer: response out
Short-circuiting: answering without the view
Middleware can return a response without calling get_response. The view (and every inner layer) never runs. That's how you build maintenance modes, IP blocks or simple rate limits:
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"],
MIDDLEWARE=["urls.MaintenanceMiddleware"], MAINTENANCE_MODE=True)
django.setup()
from django.conf import settings
from django.http import HttpResponse
from django.urls import path
from django.test import Client
class MaintenanceMiddleware:
allowed_prefixes = ("/status/",)
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if settings.MAINTENANCE_MODE and not request.path.startswith(self.allowed_prefixes):
return HttpResponse("Back soon - we're upgrading!", status=503)
return self.get_response(request)
urls.MaintenanceMiddleware = MaintenanceMiddleware
urls.urlpatterns = [
path("", lambda request: HttpResponse("Home page")),
path("status/", lambda request: HttpResponse("status: upgrading")),
]
c = Client()
for url in ["/", "/status/"]:
r = c.get(url)
print(url, r.status_code, r.content.decode())/ 503 Back soon - we're upgrading!
/status/ 200 status: upgrading
Custom settings like MAINTENANCE_MODE are allowed — any upper-case name in your settings is available as settings.NAME.
Adding data to the request
Middleware often attaches information to request for views to use, the way AuthenticationMiddleware adds request.user:
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"],
MIDDLEWARE=["urls.LanguageMiddleware"])
django.setup()
from django.http import HttpResponse
from django.urls import path
from django.test import Client
class LanguageMiddleware:
supported = {"en", "vi", "fr"}
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
header = request.headers.get("Accept-Language", "")
first = header.split(",")[0].split("-")[0].strip().lower()
request.lang = first if first in self.supported else "en"
response = self.get_response(request)
response["Content-Language"] = request.lang
return response
urls.LanguageMiddleware = LanguageMiddleware
GREETINGS = {"en": "Hello", "vi": "Xin chào", "fr": "Bonjour"}
urls.urlpatterns = [path("", lambda request: HttpResponse(GREETINGS[request.lang]))]
c = Client()
for header in ["vi-VN,vi;q=0.9", "fr", "de-DE", ""]:
r = c.get("/", headers={"Accept-Language": header})
print(f"{header!r:<18} -> {r.content.decode()} ({r['Content-Language']})")'vi-VN,vi;q=0.9' -> Xin chào (vi)
'fr' -> Bonjour (fr)
'de-DE' -> Hello (en)
'' -> Hello (en)
(Django has real internationalisation support with LocaleMiddleware; this is just a small illustration.)
Optional hooks
Class-based middleware can define extra methods that Django calls at specific moments:
| Hook | Called | Typical use |
|---|---|---|
process_view(request, view_func, args, kwargs) |
just before the view runs | inspect which view will handle the request |
process_exception(request, exception) |
when the view raises | log errors, return a custom error page |
process_template_response(request, response) |
for TemplateResponse objects |
change the template or context late |
Tip: Middleware runs for every request, including static files in development and health checks. Keep it fast, and if something only matters for a few views, a decorator or mixin is the better tool.
Test yourself
In which order do request-phase middleware run?
- Bottom to top of MIDDLEWARE
- Top to bottom of MIDDLEWARE
- Random
- Alphabetical
How can middleware stop a request from reaching the view?
- Raise StopIteration
- Return a response without calling
get_response - Delete request.path
- It cannot
Why must AuthenticationMiddleware come after SessionMiddleware?
- Alphabetical order
- It reads the logged-in user's id from the session
- It's faster
- It doesn't matter