Middleware in Django helps process requests and responses automatically. It acts like a helper that can change or check things before your app handles a request or sends a response.
0
0
Built-in middleware overview in Django
Introduction
You want to add security checks to every web request.
You need to manage user sessions across pages.
You want to handle errors or redirects globally.
You want to compress responses to make pages load faster.
You want to add headers or cookies to all responses.
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 Django settings file.
Order matters: middleware runs in the order listed for requests, and reverse order for responses.
Examples
This example shows just two middleware for security and session management.
Django
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
]This example adds common HTTP features and CSRF protection.
Django
MIDDLEWARE = [
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
]Sample Program
This is a typical middleware list in Django settings. It shows the built-in middleware that handle common tasks automatically.
Django
# settings.py snippet 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', ] # Explanation: # This setup enables security features, session handling, common HTTP tweaks, # CSRF protection, user authentication, message support, and clickjacking protection. # When a request comes in, Django runs these middleware in order. # When sending a response, it runs them in reverse order.
OutputSuccess
Important Notes
Middleware can slow down requests if too many are used, so keep only what you need.
You can write your own middleware to add custom behavior.
Always test middleware order if you add or remove items, as it affects behavior.
Summary
Middleware helps process requests and responses automatically in Django.
Built-in middleware cover security, sessions, CSRF, authentication, and more.
Order of middleware matters for how they run.