0
0
DjangoConceptBeginner · 3 min read

What is Middleware in Django: Explanation and Example

In Django, middleware is a way to process requests and responses globally before they reach your views or after they leave your views. It acts like a chain of components that can modify or handle requests and responses, such as adding headers or managing sessions.
⚙️

How It Works

Think of middleware in Django as a set of filters or checkpoints that every web request and response passes through. When a user sends a request to your website, it first goes through each middleware component in order. Each middleware can look at the request, change it, or even stop it before it reaches your main code (the views).

After your view processes the request and creates a response, the response goes back through the middleware chain in reverse order. Middleware can then modify the response before it is sent back to the user. This is like having a series of helpers that can add or change things on the way in and out, such as checking if a user is logged in, compressing data, or adding security headers.

💻

Example

This example shows a simple custom middleware that prints a message when a request starts and when a response is returned.
python
from django.utils.deprecation import MiddlewareMixin

class SimplePrintMiddleware(MiddlewareMixin):
    def process_request(self, request):
        print('Request started')

    def process_response(self, request, response):
        print('Response returned')
        return response
Output
Request started Response returned
🎯

When to Use

Use middleware when you want to apply a function to every request or response in your Django app without repeating code in every view. Common uses include:

  • Handling user authentication or permissions globally
  • Adding or modifying HTTP headers for security or caching
  • Logging or tracking requests
  • Compressing responses to save bandwidth
  • Redirecting users based on conditions

Middleware is great for cross-cutting concerns that affect many parts of your app.

Key Points

  • Middleware processes requests before views and responses after views.
  • It works like a chain where each middleware can modify or stop the flow.
  • You can write custom middleware to add your own logic.
  • Django includes many built-in middleware for common tasks.

Key Takeaways

Middleware lets you handle requests and responses globally in Django.
It works by processing requests before views and responses after views.
Use middleware for tasks like authentication, logging, and modifying headers.
You can create custom middleware by defining methods to process requests and responses.