What is process_response in Django Middleware Explained
process_response is a method in Django middleware that runs after a view returns a response. It lets you modify or inspect the HttpResponse before it is sent to the user’s browser.How It Works
Think of Django middleware as a series of checkpoints that a web request and response pass through. The process_response method is like the last checkpoint on the way back to the user. After your view function creates a response, this method can change or add things to that response before it reaches the browser.
Imagine sending a letter: the view writes the letter, and process_response is like a final review where you can add a stamp or a note before mailing it. This method receives both the original request and the response, so it can make decisions based on either.
Example
This example shows a simple middleware that adds a custom header to every response.
from django.utils.deprecation import MiddlewareMixin class CustomHeaderMiddleware(MiddlewareMixin): def process_response(self, request, response): response['X-Custom-Header'] = 'Hello from middleware' return response
When to Use
Use process_response when you want to change or add information to every response your Django app sends. Common uses include adding security headers, setting cookies, or logging response details.
For example, you might add a header to tell browsers to only use HTTPS, or you might log how long it took to create the response. It’s useful when you want to apply changes globally without modifying each view.
Key Points
- Runs after the view returns a response.
- Can modify or replace the
HttpResponseobject. - Receives both the request and response objects.
- Must always return a response object.
- Useful for adding headers, cookies, or logging.
Key Takeaways
process_response lets middleware modify responses before they reach the user.process_response.