How to Create Custom Middleware in Django: Simple Guide
To create custom middleware in Django, define a class with an __init__ and a __call__ method that processes requests and responses. Then add your middleware class path to the
MIDDLEWARE list in settings.py.Syntax
A custom middleware in Django is a class with two main parts:
- __init__(self, get_response): Called once when the server starts, it receives the next middleware or view as
get_response. - __call__(self, request): Called on each request, it can modify the request before passing it on and modify the response before returning it.
You return the response object at the end.
python
class CustomMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Code before view (request processing) response = self.get_response(request) # Code after view (response processing) return response
Example
This example middleware adds a custom header to every HTTP response.
python
class SimpleHeaderMiddleware: 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 # Add 'path.to.SimpleHeaderMiddleware' to MIDDLEWARE in settings.py
Output
When you make a request, the HTTP response will include the header:
X-Custom-Header: Hello from middleware
Common Pitfalls
- Not calling
get_response(request)inside__call__will break request processing. - Modifying the request or response incorrectly can cause errors or unexpected behavior.
- For older Django versions (before 1.10), middleware used a different style; always use the new style middleware.
python
from django.http import HttpResponse class WrongMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Forgot to call get_response return HttpResponse('Blocked') # This stops all views class CorrectMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response
Quick Reference
Steps to create custom middleware:
- Define a class with
__init__(self, get_response)and__call__(self, request). - Process request before calling
get_response(request). - Process response after calling
get_response(request). - Add the middleware class path to
MIDDLEWAREinsettings.py.
Key Takeaways
Custom middleware is a class with __init__ and __call__ methods to process requests and responses.
Always call get_response(request) inside __call__ to continue processing the request.
Add your middleware class path to the MIDDLEWARE list in settings.py to activate it.
Use the new style middleware introduced in Django 1.10 and later for best compatibility.
Middleware can modify requests before views and responses after views for flexible control.