Django Middleware

Django Middleware is a framework component in Django that processes requests and responses globally. Middleware acts as a layer of hooks or logic that is executed during the request and response cycle, allowing you to add functionality that applies across your entire application.

How Middleware Works

When a request comes into a Django application:

1. Middleware processes the request before it reaches the view.

2. After the view processes the request, middleware processes the response before it is sent back to the client.

What Middleware Can Do

Session Management: Manage user sessions across requests.

Authentication: Check if a user is logged in and authorized.

Logging: Record requests and responses for debugging or analytics.

Security Enhancements: Add headers like X-Frame-Options or Content-Security-Policy.

Custom Logic: Add application-specific behavior, like modifying responses or tracking user activity.

Type of Middleware

Django provides several middleware options

SecurityMiddleware: Adds security-related headers.

SessionMiddleware: Enables session management.

AuthenticationMiddleware: Associates users with requests.

CommonMiddleware: Provides various utilities like handling www. prefixes or trailing slashes.

How to create Custom Middleware

Step 1: Create the Middleware

1. Inside your app (e.g., myapp), create a new file called middleware.py.

2. Add the following code:


# myapp/middleware.py

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

    def __call__(self, request):
        # This code runs before the view is called
        print(f"Request URL: {request.path}")

        # Call the next middleware or view
        response = self.get_response(request)

        # This code runs after the view is called
        return response

Step 2: Add Middleware to settings.py

In your project’s settings.py, add the middleware class to the MIDDLEWARE list:


MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # Add your custom middleware here
    'myapp.middleware.LogURLMiddleware',
]

Step 3: Run the Server

Start the Django development server:


python manage.py runserver

When you visit any URL, Django will print the requested URL in the terminal. For example:


Request URL: /
Request URL: /about/
Request URL: /contact/