In Django, middleware allows you to process request and response objects globally before they reach the view or after the view has processed the response. These objects are the backbone of how Django handles incoming data and sends responses back to the client.
The request object provides access to HTTP methods, headers, user data, cookies, and payload. The response object allows modification of headers, status codes, cookies, and content before sending data back to the client.
# Middleware to log request information
class RequestLoggingMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
method = request.method
user = request.user
headers = request.headers
print(f"Request Method: {method}")
print(f"User: {user}")
print(f"Headers: {headers}")
response = self.get_response(request)
return response
# Middleware to add a custom response header
class CustomHeaderMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
response['X-Custom-Header'] = 'This is a custom header'
return response
# Middleware to inject custom data into request
class AddContextToRequestMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
request.custom_data = 'This is some custom data'
response = self.get_response(request)
return response
The middleware executes for every request. Request data can be logged or modified before reaching views, and response headers or content can be altered before returning to the client.
Client ➜ Middleware (Request) ➜ View ➜ Middleware (Response) ➜ Client
Configure middleware and click "Send Request" to watch the execution order.
get_response(request).