Types of Middleware in Django

Django’s middleware can be divided into 2 types: built-in and custom.

Built-in Django Middleware: Django comes with a set of built-in middleware classes. These are some of the most commonly used default middleware classes in Django:

  • SecurityMiddleware: It provides several security-related features such as ensuring that all HTTP requests are redirected to HTTPS and is used to add security headers to responses.
  • SessionMiddleware: It helps in managing sessions for users. It enables Django to handle session data, making it available to views and templates.
  • CommonMiddleware: Handles common operations such as URL redirection (adding/removing “www” prefix), appending slashes to URLs.
  • CsrfViewMiddleware: Enables protection against Cross-Site Request Forgery (CSRF) attacks. It adds and verifies a CSRF token in POST requests to protect against malicious requests from other sites.
  • AuthenticationMiddleware: Adds the user' attribute to the request, representing the currently logged-in user, if applicable. It also manages the user’s session and authentication state.

Sample middleware already included in ‘setting.py’

Custom Middleware: These are the middleware that a user creates for their purpose. It can be built as a class-based style with a call method that processes requests and responses or as a function style that accepts a get_response callable. It is produced in the middleware.py file. A middleware is turned on by including it in the Django settings’ MIDDLEWARE list.

Middleware in Django [image, Video error]

Middleware is a series of processing layers present between the web server and the view (controller in some frameworks), allowing the user to intercept, modify, and add behavior to these requests and responses.

Similar Reads

What is Middleware in Django?

In Python Django, middleware is a framework that provides a method to process requests and responses globally before they are processed by the view or after they leave the view. Middleware components are designed so that they remain between the web server and the view, allowing us to perform various operations on requests and responses as they pass through the Django application and web browser....

Types of Middleware in Django

Django’s middleware can be divided into 2 types: built-in and custom....

Create Custom Middleware in Django

Let us look at an example in we are creating a middleware in a django project.Suppose there are three types of users such as teacher,student and principal.The main motive behind creating middleware is that it diverges the request according the types of user it is ,such as the teacher after login on the website lands on the teachers homepage and same in this way the principal lands on the principal home page and similarly for the student....