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 setting.py

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

settings.py

....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core',
]

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',

    '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/middleware.py file and add.

core/middleware.py
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 Tuts-Station.com</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/views.py file and add.

core/views.py
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:

core/templates/home.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home</title>
</head>
<body>
<div class="container" style="text-align: center;">
    <h1>Home</h1>
    <p>Django Custom Middleware Example</p>
</div>
</body>
</html>
Step 7: Creating URLs

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

core/urls.py
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.

example/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    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 manage.py runserver

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



I Hope It will help you....