← Back to Chapters

Django Middleware

? Django Middleware

? Quick Overview

Middleware in Django provides a powerful mechanism to process requests and responses globally. It allows developers to hook into Django’s request/response lifecycle to apply logic before the view executes and after the response is generated.

? Key Concepts

  • Acts as a bridge between request and response
  • Executed in a defined order
  • Can modify request or response objects
  • Used for cross-cutting concerns

? What is Middleware?

In Django, middleware is a framework of hooks into the request/response processing. It is a lightweight, low-level plugin system for globally altering Django’s input or output.

⚙️ How Middleware Works

Middleware components are executed in the order they are listed in the MIDDLEWARE setting. Each middleware can implement lifecycle methods that hook into request handling.

  • __init__ – Runs once when the server starts
  • __call__ – Runs for each request
  • process_request – Runs before the view
  • process_response – Runs after the view

? Code Example

? View Code Example
# Custom middleware to log request processing time
import time

class SimpleLoggingMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        start_time = time.time()
        response = self.get_response(request)
        duration = time.time() - start_time
        print(f"Request took {duration:.2f} seconds")
        return response

? Live Output / Explanation

This middleware calculates the time taken for each request and prints it to the server console, helping developers analyze performance.

? Interactive Middleware Simulator

Click "Send Request" to see how data flows through the "Onion Architecture" of Middleware.

Request
Security MW
Log MW
View (DB)
> Server Ready. Waiting for request...

? Interactive Concept Flow

Request ➜ Middleware ➜ View ➜ Middleware ➜ Response

? Common Use Cases

  • Request logging
  • User authentication
  • Session handling
  • Security enforcement
  • Response modification

✅ Tips & Best Practices

  • Keep middleware lightweight
  • Be careful with execution order
  • Use only for global behavior

? Try It Yourself

  • Create middleware to block specific IPs
  • Add custom headers to responses
  • Measure API response times