How Django Middleware Works?

Welcome to my Blog, in this article we learn about How Django Middleware Works?

Django Middleware is a lightweight, low-level plugin system that modifies Django’s input and output. It is a framework that integrates Django for the processing of queries and answers. You can use middleware if you want to change the request object.

Django maintains a list of middleware for each project. Middleware allows you to edit requests from the browser before they reach Django, and to view the response from the view before they reach the browser. The middleware is applied in the same order as it is added to the list in the Django settings. If a new Django project has added a number of middlewares, in most cases they cannot be removed. Middleware is a checkmark that modifies the Django query and response objects.

In order for middleware to play a role, it is dependent on other middleware. For example, AuthenticationMiddleware stores the authenticated user session and executes the SessionMiddleware. For example, here are the default values that the Django admin has created for when you start project command setup:

Click to View Django Middleware in Official Documentation

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

How does Django Middleware work?

The Django Middlewares works process the request before going to create a custom Django middleware.

The picture shows the working of Django middlewares.

working of django middlewares
working of django middlewares
How Django Middleware Works?
another example of django middleware

Django applies the above middleware from top to bottom. The middleware classes of each level are wrapped in the view function. The queries are passed successively through the layers and the response generated by the query goes to the layer that executed the query.

Suppose we have a Django app with the following models.py file. Create a file where you can define your custom middleware using the model above. The only thing we have to worry about is that there are 2 hooks for the request and 3 hooks for the response. In order to write the middleware, we only need to define one or more of the above functions for our needs.

before calling the view, in request phase, there are 2 hooks for the request:

  • process_request()
  • process_view()

After calling the view, in the response phase, there are 3 hooks for the request:

  • process_exception()
  • process_template_response()
  • process_response()

Read More : how to integrate CKEditor in Django

Read More : Django admin full Customization step by step

Read More : How model queries work in Django

Read More : How to make Chatbot in Python?

#models.py

from __future__ import unicode_literals
from django.db import models

# Create your models here.

class Movies(models.Model):
  first_name = models.CharField(max_length=50)
  last_name = models.CharField(max_length=50)
  release_date = models.DateTimeField(default=datetime.now, blank=True)
  
  def __unicode__(self):
    return self.first_name

#moviemiddleware.py

from .models import Movies

class GetMovies(object):
  def process_request(self, request):
    print ('"The Dark Knight is the best superhero movie of all time"')


#settings.py
MIDDLEWARE = [
    'movies.moviemiddleware.GetMovies',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

Structure of a basic Middleware in Django

class ExampleMiddleware:

    def _init_(self, get_response):
        self.get_response = get_response

    def _call_(self, request):

        # Code that is executed in each request before the view is called

        response = self.get_response(request)

        # Code that is executed in each request after the view is called
        return response

    def process_view(self, request, view_func, view_args, view_kwargs):
        # This code is executed just before the view is called

    def process_exception(self, request, exception):
        # This code is executed if an exception is raised

    def process_template_response(self, request, response):
        # This code is executed if the response contains a render() method
        return response

This is where our real middleware logic comes in. As you can see in the code above, our constructor has one parameter, namely the get _response function. This parameter is passed from the Django framework to our middleware and is used to pass the request object to the next middleware that receives the value of the response. It also turns the object into a retrievable object. When this method is called, the framework calls the middleware.

Django Middleware Hooks Methods:

Request Preprocessor ( process_request ): This request preprocessor method is called when a request is received and Django analyzes the URL and determines which view to execute. An HttpRequest object is passed, which you can change at will. When the preprocessor returns an HttpResponse object, When Django calls any other middleware, but simply types in the corresponding view. If there is None, the request will be processed further and the middleware executed in the appropriate view.

Uses for Middlewares:

  1. Filtering Requests
  2. Injecting Data into Requests
  3. Performing Logging, Analytics and Other Miscellaneous Tasks
class JSONTranslationMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        self.translations = {
            "en": {"greeting": "Hello", "header": "Welcome Django!"},
            "nl": {"greeting": "Hallo", "header": "Welkom Django!"},
        }

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

    def process_template_response(self, request, response):
        response.context_data["translations"] = self.translations
        return response

I have to place self-translation in the context of the view. The middleware offers hooks to carry out context manipulations. These hooks pick up the query/answer and access the context (ResponseContext data). The new Django context is the data that the view transmits to the user. A middleware hook is a class or method that intercepts the Django reaction of a view during its life cycle.

if you liked the article and share it with your friends and if you have any questions about the article feel free to leave me a comment and I will answer the question you have and that’s about it hopefully I will see you again in another article.

7 thoughts on “How Django Middleware Works?

  • May 11, 2021 at 1:34 pm
    Permalink

    What’s up to every one, it’s really a fastidious for me to visit this site, it contains useful Information.

    Reply
  • July 21, 2021 at 9:59 am
    Permalink

    For most up-to-date information you have to visit internet and on the web I found this site as a most excellent
    site for newest updates.

    Reply
  • July 22, 2021 at 1:24 am
    Permalink

    Can you tell us more about this? I’d want to find out some additional information.

    Reply
  • July 22, 2021 at 2:51 pm
    Permalink

    Hi it’s me, I am also visiting this site regularly,
    this website is truly fastidious and the people are in fact sharing nice thoughts.

    Reply
  • July 24, 2021 at 5:18 pm
    Permalink

    Hello just wanted to give you a brief heads up
    and let you know a few of the images aren’t loading correctly.

    I’m not sure why but I think its a linking issue. I’ve tried it in two different browsers and both show the same outcome.

    Reply

Leave a Reply

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