2

I'm working on Django (v1.11) project and need to provide some middleware functionality to the site. This version of Django modify old MIDDLEWARE_CLASSES setting as described in docs:

A new style of middleware was introduced for use with the new MIDDLEWARE setting.

However, I can't understand how NEW middleware works. After reading the middleware's documentation I come to the following conclusion:

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

    def __call__(self, request):
        return self.get_response(request)

    def process_template_response(self, request, response):
        # do something here
        return response

I thought that it'll work, but unfortunately code above doesn't work and is completely ignored by Django (without any error!).


When I do something like the following:

class FooMiddleware(object):    
    def process_template_response(self, request, response):
        # do something here
        return response

...an error occured (because __init__ method of object class has no arguments):

TypeError: object() takes no parameters


When I change the code as follows everything works:

from django.utils.deprecation import MiddlewareMixin

class FooMiddleware(MiddlewareMixin):
    def process_response(self, request, response):
        # do something here
        return response

But! The MiddlewareMixin is related to the deprecation utils and used for compatibility purposes:

Django provides django.utils.deprecation.MiddlewareMixin to ease creating middleware classes that are compatible with both MIDDLEWARE and the old MIDDLEWARE_CLASSES.


Question: How to properly define a middleware class in Django v1.11?

cezar
  • 11,616
  • 6
  • 48
  • 84
Yurii Rabeshko
  • 591
  • 8
  • 17

1 Answers1

3

Defining process_template_response is only useful if your response instance has a render() method. If not, you should move your custom code into the __call__ method.

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

    def __call__(self, request):
        response = self.get_response(request)
        # Do something here
        return response
Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • [Alasdair](https://stackoverflow.com/users/113962/alasdair), thanks. I thought that the `process_template_response` method is replacement for the old `process_response` method. – Yurii Rabeshko Aug 21 '17 at 15:37