Django Middleware


Middleware in Django is a framework that allows code to hook into the response / request processing and alter the input or output of Django.


Middleware needs to be added to your MIDDLEWARE_CLASSES list before it will be included in execution. The default list that Django provides when creating a new project is as follows:


These are all functions that will run in order on every request (once before it reaches your view code in and once in reverse order for process_response callback, before version 1.10). They do a variety of things such as injecting the Cross Site Request Forgery (csrf) token.

The order matters because if some middleware does a redirect, then the all the subsequent middleware will never run. Or if a middleware expects the csrf token to be there, it has to run after the CsrfViewMiddleware.