0
0
Djangoframework~3 mins

Creating custom middleware in Django - Why You Should Know This

Choose your learning style9 modes available
The Big Idea

What if you could control every web request with just one simple piece of code?

The Scenario

Imagine you want to check every web request to your Django app for a special token or log details before the page loads.

You try adding this check inside every view function manually.

The Problem

Manually adding checks in every view is tiring and easy to forget.

It leads to repeated code and bugs if you miss a spot.

Updating the logic means changing many places, which wastes time and causes errors.

The Solution

Custom middleware lets you write one piece of code that runs automatically on every request or response.

This keeps your code clean, consistent, and easy to update.

Before vs After
Before
def my_view(request):
    if not check_token(request):
        return error_response()
    # rest of view code
After
class TokenCheckMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
    def __call__(self, request):
        if not check_token(request):
            return error_response()
        response = self.get_response(request)
        return response
What It Enables

You can control and modify all requests and responses in one place, making your app more secure and maintainable.

Real Life Example

Many websites use middleware to log user activity or block bad requests before they reach the main app logic.

Key Takeaways

Manual checks in every view cause repeated code and errors.

Custom middleware runs code automatically on all requests.

This makes your app easier to maintain and more reliable.