Everything you need to know about Middleware in Django!

Akash Shrivastava

Hey, there fellow Djangomers and Pythonistas,

At ScaleReal we work extensively on Python/Django Applications and have built a lot of highly scalable applications for various clients of ours.

While working on such apps it’s very important to understand the ins and outs of Django’s middleware workings.

So, In this article, we’ll learn about Middleware in Django, why to use them, how it works & how to create custom middleware in Django. So, let’s dive in!

Here’s a list of everything which will be covered in this article:

  1. What is Middleware in Django?

  2. How does Middleware work?

  3. What are the types of Middleware?

  4. How to write a custom Middleware in Django?

  5. Things to remember when using middleware

1. What is Middleware in Django?

In Layman terms 👨‍💼, a Middleware is something which acts as a bridge between two parts of a program or the system that enables communication between them. In technical terms 👨‍💻, Middleware is a framework of hooks into Django’s request/response processing. It’s a light, low-level “plugin” system for globally altering Django’s input or output. Each middleware component is responsible for doing some specific function.

2. How does Middleware work? 🤔

When a user makes a request from your application, a WSGI handler is instantiated, which handles the following things:

  • Imports project’s settings.py file and Django exception classes.
  • Loads all the middleware classes which are written in MIDDLEWARE tuple located in settings.py file
  • Builds list of methods which handle processing of request, view, response & exception.
  • Loops through the request methods in order.
  • Resolves the requested URL
  • Loops through each of the view processing methods
  • Calls the view function
  • Processes exception methods (if any)
  • Loops through each of the response methods in the reverse order from request middleware.
  • Builds a return value and makes a call to the callback function.

Working of Middleware ⬇⬆

3. What are the types of Middleware?

There are two types of Middleware in Django:

  • Built-in Middleware
  • Custom Middleware

Built-in Middleware are provided by default in Django when you create your project. You can check the default Middleware in settings.py file of your project.