Django Create Custom Middleware Example

Published On: 12/01/2023 | Category: Django

Hi Dev,

In this tutorial, I will show you how to create a custom django middleware. In this article, we will implement a django custom middleware. This tutorial will give you simple example of create custom middleware django. let’s discuss about how to create custom middleware in django.

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.

A middleware factory is a callable that takes a get_response callable and returns a middleware. A middleware is a callable that takes a request and returns a response, just like a view.

Here i will give you we will help you to give example of how to create a custom django middleware. So let's see the bellow example:

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2: Create an App

Now we'll create a single app called core to store a list of post names. We're keeping things intentionally basic. Stop the local server with Control+c and use the startapp command to create this new app.

cd example
django-admin startapp core
Step 3: Update

Then update INSTALLED_APPS within our file to notify Django about the app.



    'core.middleware.CustomMiddleware' #Add line
Step 4: Creating the Middleware

In this step, we need to configure create a new middleware file in our core app. open the core/ file and add.

class CustomMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):

        print("custom middleware before next middleware/view")
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)

        response.write("<p></p><hr/><div style='color:blue;text-align:center'>Welcome to</div>")

        # Code to be executed for each response after the view is called
        print("custom middleware after response or previous middleware")
        return response
Step 5: Creating the Views

In this step, we need to configure views. open the core/ file and add.

from django.shortcuts import render

# Create your views here.
def my_view(request):
    return render(request, 'home.html')
Step 6: Creating the Templates

Next, then with your text editor create new templates files: core/templates/home.html file and the add:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
<div class="container" style="text-align: center;">
    <p>Django Custom Middleware Example</p>
Step 7: Creating URLs

In this section, we need a file within the core app however Django doesn't create one for us with the startapp command. Create core/ with your text editor and paste below code.

from django.urls import path
from . import views

urlpatterns = [
    path('home', views.my_view, name='index'),

Next, we require to add a URL path for our core app which can be done by importing include and setting a path for it.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('core.urls')),
Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python runserver

Next, go to the http://localhost:8000/home address with a web browser.

I Hope It will help you....