Basic Custom Middleware

A snippet showing how to write a basic custom middleware.


# middleware.py

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

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

# settings.py

MIDDLEWARE = [
    # ...
    'your_app.middleware.BasicMiddleware',
]
  

# views.py

from django.http import HttpResponse

def home(request):
    return HttpResponse("OK")
  
Explanation:
  • A middleware is a callable that gets request, returns a response, and sits in the global request/response pipeline.
  • __init__(get_response) runs once at server start; __call__(request) runs per request.
  • Add the path to MIDDLEWARE in settings.py to activate it for all requests.
  • Start simple like this, then add request preprocessing or response postprocessing as needed.
  • Category Middleware
  • Total Views 1041
  • Last Modified 19 February, 2026
  • Tags #middleware #request #response #basics
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.