Django Middleware
Details
Middleware in Django is a series of components that sit between the user's request and your final response. Think of it as a set of filters or checkpoints that inspect or modify the data passing through them.
Each middleware piece has a chance to process what’s going in or coming out of your application.
What Does Middleware Do?
Middleware can:
- Block or allow requests
- Alter responses before they reach the browser
- Handle redirection or error handling
- Inject headers or cookies
- Perform logging or analytics
- Manage authentication behind the scenes
Where Middleware Lives
Middleware is listed in your project’s settings file. Open settings.py and locate the MIDDLEWARE section:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
...
] Each item is a class path. Django runs them from top to bottom when receiving a request, and in reverse order when sending the response back.
Writing Your Own Middleware
To create a custom one, write a class with two methods: __init__() and __call__() or process_*() methods.
Example:
class SimpleLoggerMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
Print(f"Accessing: {request.path}")
response = self.get_response(request)
return response To activate it, add the path in the MIDDLEWARE list:
members.middleware.SimpleLoggerMiddleware',
Types of Middleware Hooks
There are various points you can plug into:
- process_request(self, request) – runs before view logic
- process_view(self, request, view_func, view_args, view_kwargs) – triggers right before view executes
- process_exception(self, request, exception) – handles errors from views
- process_response(self, request, response) – edits what gets returned
These are optional. You can define only what you need.
Built-in Middleware Examples
Here are a few built-in ones and what they do:
- SessionMiddleware – tracks user sessions
- AuthenticationMiddleware – attaches user data to requests
- CsrfViewMiddleware – guards against cross-site request forgery
- CommonMiddleware – adds useful headers and redirects
- SecurityMiddleware – enforces security-related headers
Order Matters
Since middleware stacks act in sequence, their order in the list changes how your app behaves. For example, authentication should run after sessions are enabled.
Summary
- Middleware runs during both request and response phases
- Each class can inspect, change, or stop requests/responses
- You can use built-ins or create your own
- Add them in settings.py under MIDDLEWARE
- They’re helpful for logging, security, session handling, and more
Prefer Learning by Watching?
Watch these YouTube tutorials to understand HTML Tutorial visually:
What You'll Learn:
- 📌 Django Middleware Explained | Creating Custom Middleware in Django
- 📌 What is Middleware?