Middleware in Django is a framework that allows code to hook into the response / request processing and alter the input or output of Django.
Middleware needs to be added to your settings.py MIDDLEWARE_CLASSES
list before it will be included in execution. The default list that Django provides when creating a new project is as follows:
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
These are all functions that will run in order on every request (once before it reaches your view code in views.py
and once in reverse order for process_response
callback, before version 1.10). They do a variety of things such as injecting the Cross Site Request Forgery (csrf) token.
The order matters because if some middleware does a redirect, then the all the subsequent middleware will never run. Or if a middleware expects the csrf token to be there, it has to run after the CsrfViewMiddleware
.