Categories
Python Answers

How to set up custom middleware in Python Django?

Spread the love

Sometimes, we want to set up custom middleware in Python Django.

In this article, we’ll look at how to set up custom middleware in Python Django.

How to set up custom middleware in Python Django?

To set up custom middleware in Python Django, we create our own class.

For instance, we write

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

    def __call__(self, request):
        #...
        response = self.get_response(request)
        return response

    def process_view(self, request, view_func, view_args, view_kwargs):
        #...
        return None

    def process_exception(self, request, exception):
        #...
        return None

    def process_template_response(self, request, response):
        #...
        return response

to create the CustomMiddleware class.

We add the __init__ method to initialize the middleware.

__call__ is called on each request.

process_view is called before Django calls the view.

process_exception is called when a view raises an exception.

And process_template_response is called after the view finished executing.

Then we activate our middleware by putting it in the MIDDLEWARE list in the settings.py file.

We write

MIDDLEWARE = [
    # ...
    # Add your custom middleware
    'path.to.your.middleware.CustomMiddleware',
]

to add our CustomMiddleware class into the list.

Conclusion

To set up custom middleware in Python Django, we create our own class.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *