Writing middleware in Django>=1.10
Since Django 1.10, a middleware class must accept a get_response
argument in its __init__()
method and provide a __call__()
method. Although this can be achieved by using the django.utils.deprecation.MiddlewareMixin
when defining a middleware class (as shown in the answer by W.Perrin), creating a class-based middleware in the currently supported versions of Django looks like this:
class CustomMiddleware(object):
def __init__(self, get_response):
"""
One-time configuration and initialisation.
"""
self.get_response = get_response
def __call__(self, request):
"""
Code to be executed for each request before the view (and later
middleware) are called.
"""
response = self.get_response(request)
return response
def process_view(self, request, view_func, view_args, view_kwargs):
"""
Called just before Django calls the view.
"""
return None
def process_exception(self, request, exception):
"""
Called when a view raises an exception.
"""
return None
def process_template_response(self, request, response):
"""
Called just after the view has finished executing.
"""
return response
The process_view()
, process_exception()
and process_template_response()
are special hooks, called by Django when processing the middleware, you may define in your middleware class. In the example above, the implemented hooks will do nothing special expect for making sure that Django will call the next middleware to further process the response/request.
Activating middleware
To activate the middleware component, add it to the MIDDLEWARE
list in your Django settings.
MIDDLEWARE = [
# Default 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',
# Add your custom middleware
'path.to.your.middleware.CustomMiddleware',
]