Srikanth Technologies

Creating Custom Middleware in Django

In this blog, we understand what is middleware and how to create a custom middleware in Django.

I assume we have a django project called webdemo and an application called demo. Here we discuss how to create and use a custom middleware in webdemo project. However, you can create a custom middleware in any Django project by following the steps given below.

What is Middleware?

Middleware is a way to hook some functionality into request/response processing of Django Framework.

Each middleware is meant to perform some process either before request is processed or/and after request is processed.

This is similar to Filter concept in Java EE.

Creating Custom Middleware

Here are the steps to create a custom middleware that is used to add copyright information at the end of all responses.

Create function called footer() in module footer_middleware.py. The function footer() is supposed to return a function (middleware() in this case) that is to be hooked in request pipeline.

The function returned by footer() must itself return an object of type Response.

It is also calling get_response() method to get access to response after view is processed.

webdemo/footer_middleware.py

def footer(get_response):
    # Do one-time configuration and initialization here

    # this function is called for every view
    def middleware(request):
        # do required process before the view is called here

        response = get_response(request)   # Call view and get response

        # Add copyright message at the end of output generated by view 
        response.write("<p></p><hr/><div style='color:blue;text-align:center'>Copyright © Srikanth Technologies. All rights reserved.</div>")

        return response   # return response object

    return middleware   # return the function that is to be called to hook process 

Configure settings.py

Include custom middleware in settings.py so that middleware is attached to every request in the project.

MIDDLEWARE = [
    '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',
    'webdemo.footer_middleware.footer', 
]

Using Custom Middleware

Now lets see how this middleware works. We create a simple function view, template and link a url with the view.

demo/view.py

from django.shortcuts import render

def about(request):
    return render(request, 'about.html')

demo/templates/about.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>About</title>
</head>
<body>
<h1>About</h1>
Using custom middleware!
</body>
</html>

webdemo/url.py

Associate all URLs that start with /demo with demo.urls.

from django.urls import path, include

urlpatterns = [
    path('demo/', include('demo.urls')),
]

demo/url.py

Associate about view with /about url.

from django.urls import path
from . import views

urlpatterns = [
    path('about/', views.about),
]

Now, when you run any view http://localhost:8000/demo/about in the project, at the end of response, custom middleware that was created and registered in the project will attach footer.

Download Source Code

You can access complete source code (webdemo.rar), which contains webdemo project with demo application.

In order to go through the complete source code, first unzip webdemo.rar file into a folder. It will create webdemo (project) folder and inside that another folder for demo application.

Start PyCharm IDE and select File -> Open and then select webdemo folder to open project in PyCharm.

For more information about custom middleware, refer to Django Documentation