Yurii Rabeshko
Yurii Rabeshko

Reputation: 631

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

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?

Upvotes: 2

Views: 794

Answers (1)

Alasdair
Alasdair

Reputation: 308849

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

Upvotes: 3

Related Questions