Django middleware is a light plugin for Django that handles request and response processing on a global scale. The middleware acts as a bridge between various program functions in Django.
Django middleware sits between the web server and the view, providing a way to add functionalities or perform actions on every incoming request or outgoing response. In simpler terms, on a global level, it handles Django's input and output. Middleware operates as a series of Python classes that get executed in a specific order for each request-response cycle.
Django middleware performs specific functions such as associating a user with a request using sessions, CORS (Cross-Origin Resource Sharing) handling, security, messaging, logging, and many more.
Django comes with a default middleware that one can use out of the box. We can also create our own custom middleware, but we will be discussing only the middleware that comes with Django.
How can we activate this middleware?
The in-built Django middleware is activated by creating django-admin startproject
.The middleware is found in the setting.py file. Each middleware is represented as a string and stored in a Python list called MIDDLEWARE:
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",
]
The inbuilt Django middleware is optional, but according to Django documentation, it's advisable to keep at least the CommonMiddleware
.
Some middleware depends on another to function properly; therefore, it's mandatory to keep the order in mind. For example, the SessionMiddleware
should come before MessageMiddleware
because the MessageMiddleware
can use session-based storage.
Finally, let's discuss the individual in-built middleware in Django.
SecurityMiddleware:
TheSecurityMiddleware
handles several security of the request/response cycle. The specific security can be enabled independently. The security includes
The SECURE_SSL_REDIRECT
redirect any HTTP connections to HTTPS when it is set to True.
SessionMiddleware:
The SessionMiddleware
enables session support. The session framework stores data on the server side and retrieves the data on a per-site visitor basis.
CommonMiddleware:
TheCommonMiddleware
includes a few extras for perfectionists:
URL normalization: It redirects URLs with trailing slashes to URLs without trailing slashes (or vice versa) based on your project's APPEND_SLASH
setting.
CsrfViewMiddleware:
The CsrfViewMiddleware
adds protection against cross-site Forgeries by adding another layer to the form field and cross-checking for the right posted values.
AuthenticationMiddleware:
The AuthenticationMiddleware
associates the session with the user's authentication status. If a user is authenticated (logged in), the middleware associates the user's information (user object) with the session. This allows the user to stay logged in during their visit to the site.
MessageMiddleware:
The MessageMiddleware
supports cookie and session-based messaging. The MessageMiddleware
ensures that messages persist across redirects and are displayed to the user on the next page they visit.
Conclusion:
Django Middleware is a light framework that handles request and response processing. Django comes with an in-built middleware. The inbuilt middleware can be activated by creating django-admin startproject
. Each inbuilt middleware is enclosed in a string and located in the setting.py files. The string gives the full Python path to the middleware factory’s class or function name. The middleware performs specific functions ranging from authentication, security, logging, and eliminating forgery.