Intermediate
What is Django's middleware and how can you create your own?
Middleware in Django is a framework of hooks into Django's request/response processing. It’s a way to process requests globally before they reach the view or after the view has processed them.
To create your own middleware, follow these steps:
- Create a new Python file, e.g.,
middleware.py
in your app directory. - Define a middleware class with
__init__
,__call__
, and/orprocess_request
methods.
Example of a simple logging middleware:
class SimpleMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
print(f'Before processing request: {request.path}')
response = self.get_response(request)
print(f'After processing request: {response.status_code}')
return response
Finally, add your middleware to the MIDDLEWARE
setting in settings.py
.