New middleware format in Django 2

MIddleware (middleware) are used to modify an incoming request object into a view or to modify a response object returned from a view. They allow us to modify requests/responses globally.

Old format middleware

Before Django 1.10, there were 5 hooks. Any class that had process_request(), process_view(), process_exception(), process_template_response() and process_response() methods could be used as middleware and specified in the setting in the  MIDDLEWARE_CLASSES parameter.

The first two calls to — process_request() and process_view() were called before the view was called. The following three methods process_exception(), process_template_response() and process_response() were executed after the view returned a response object.

New middleware format

The most important change when migrating a project to Django 2 — this change MIDDLEWARE_CLASSES to MIDDLEWARE in the file and MIDDLEWARE_CLASSES is removed.

The old middlewares must be a class, while the new ones can be any callables that receive get_response or, when responded, accept a request and return a response.

class TimeStampMiddleware(object):
     def __init__(self, get_response):
         self.get_response = get_response

     def __call__(self, request):
         request.timestamp = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
         response = self.get_response(request)
         return response

Here, get_response can be a view that returns a response, or the next middleware in the list. Therefore, the request is processed in the specified order by the middleware, and the response is processed in the reverse order.

To activate your middleware, you need to add the path to it in MIDDLEWARE in the file:


Update middleware

Django provides a mixin django.utils.deprecation.MiddlewareMixin which should extend the capabilities of the old middleware format. Thus MiddlewareMixin converts the class object into a callable. For example:

from django.utils.deprecation import MiddlewareMixin

class CustomMiddleware(MiddlewareMixin):
     def process_request(self, request):
         # Process the request

     def process_response(self, request, response):
         # Process the response
         return response


Back to Top