0
0
Djangoframework~5 mins

Middleware configuration in Django

Choose your learning style9 modes available
Introduction

Middleware lets you add extra steps to handle web requests and responses in Django. It helps you change or check data before it reaches your app or before it goes back to the user.

You want to check if a user is logged in before showing a page.
You need to add security headers to every response.
You want to log details about every request your site gets.
You want to handle errors or redirects in one place.
You want to compress responses to make pages load faster.
Syntax
Django
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

This list goes in your settings.py file.

The order matters: Django runs middleware top to bottom for requests, bottom to top for responses.

Examples
This example adds your own middleware called CustomMiddleware between built-in ones.
Django
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'myapp.middleware.CustomMiddleware',
    'django.middleware.common.CommonMiddleware',
]
This example shows a shorter list with only two middleware for common tasks and CSRF protection.
Django
MIDDLEWARE = [
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
]
Sample Program

This middleware prints the URL path of every request to the console. It is added to the MIDDLEWARE list in settings.py.

Django
from django.utils.deprecation import MiddlewareMixin

class SimpleLogMiddleware(MiddlewareMixin):
    def process_request(self, request):
        print(f"Request path: {request.path}")

# In settings.py
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'myproject.middleware.SimpleLogMiddleware',
]

# When you run the server and visit a page, the console will print the request path.
OutputSuccess
Important Notes

Middleware classes must be importable by Django, so use the full Python path.

Use middleware only for tasks that need to run on every request or response.

Remember to restart your Django server after changing middleware settings.

Summary

Middleware lets you add code that runs on every web request and response.

Configure middleware in the MIDDLEWARE list inside settings.py.

The order of middleware matters for how requests and responses are handled.