How to Use Middleware in Django: Syntax and Examples
In Django,
middleware is a way to process requests and responses globally by creating a class with __init__, __call__, or specific methods like process_request. You add your middleware class path to the MIDDLEWARE list in settings.py to activate it.Syntax
Django middleware is a class that can define methods to process requests and responses. The most common pattern is to define a __init__ method for setup and a __call__ method to handle the request and response.
Alternatively, you can define methods like process_request, process_view, process_response, and process_exception for specific hooks.
After creating the middleware class, add its full Python path to the MIDDLEWARE list in your Django settings.py file.
python
class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Code before view response = self.get_response(request) # Code after view return response
Example
This example middleware adds a custom header to every HTTP response. It shows how to create the middleware class and enable it in settings.py.
python
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'] = 'Hello from middleware' return response # In settings.py, add: # MIDDLEWARE = [ # ... # 'yourapp.middleware.CustomHeaderMiddleware', # ]
Output
When you make any HTTP request to your Django app, the response will include the header:
X-Custom-Header: Hello from middleware
Common Pitfalls
- Forgetting to add the middleware class path to the
MIDDLEWARElist insettings.pymeans the middleware won't run. - Not calling
self.get_response(request)inside__call__will block the request from reaching views. - Modifying the request or response incorrectly can cause errors or unexpected behavior.
python
from django.http import HttpResponse class BrokenMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Missing call to get_response blocks processing return HttpResponse('Blocked by middleware') # Correct way: class FixedMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response
Quick Reference
| Middleware Hook | When It Runs | Purpose |
|---|---|---|
| __init__(self, get_response) | Once when server starts | Setup middleware instance |
| __call__(self, request) | For each request | Process request and response |
| process_request(self, request) | Before view | Modify request or return response early |
| process_view(self, request, view_func, view_args, view_kwargs) | Before view | Modify view or arguments |
| process_response(self, request, response) | After view | Modify response before sending |
| process_exception(self, request, exception) | If view raises exception | Handle exceptions |
Key Takeaways
Middleware in Django is a class that processes requests and responses globally.
Always add your middleware class path to the MIDDLEWARE list in settings.py to activate it.
The __call__ method must call self.get_response(request) to continue processing.
Middleware can modify requests before views and responses after views.
Common mistakes include forgetting to add middleware or blocking requests by not calling get_response.