Enhancing Django Applications with a Custom Middleware

Enhancing Django Applications with a Custom Middleware


3 min read

I came across a bug in my secret project. This bug doesn't want to tick the boolean field in the database after a user signs up using logic in the view.

What is Middleware in Django?

A Middleware in Django is a way to process requests and responses globally in your application. It's like a set of filters that can be applied before and after views are executed. Each middleware component can perform various tasks such as authentication, modifying the request or response, and much more. A Middleware operates at a lower level than views, making it a great place to handle cross-cutting concerns.

The MiddlewareMixin is a base class that simplifies the creation of custom middleware classes. It provides a straightforward way to define a middleware class in Django.

Meet OnboardingMiddleware

In my project, I have a custom middleware class called OnboardingMiddleware. Let's take a closer look at what this middleware does and how it's used.

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import redirect
from django.urls import reverse

class OnboardingMiddleware(MiddlewareMixin):
    def __call__(self, request):
        if request.user.is_authenticated and not request.user.is_onboarded:
            if request.path != reverse('onboarding:start'):
                return redirect('onboarding:start')
        response = self.get_response(request)
        return response

The Purpose of OnboardingMiddleware

The OnboardingMiddleware class serves a specific purpose: ensuring that users who are not onboarded are redirected to the onboarding process. Let's break down how it accomplishes this:

  1. User Authentication Check: It first checks if the user is authenticated using request.user.is_authenticated. This is essential to ensure that the user is logged in.

  2. Onboarding Check: It then checks if the user is onboarded by verifying that request.user.is_onboarded is False. This is set to True in the user model when a user completes the onboarding process.

  3. Redirect to Onboarding: If the user is authenticated but not onboarded, and the current path (request.path) is not the onboarding start path, it redirects the user to the onboarding start page using redirect('onboarding:start').

  4. Pass Control to Next Middleware/View: Finally, it allows the request to continue through the middleware stack by calling self.get_response(request).

    Using OnboardingMiddleware

To use the OnboardingMiddleware in your Django project, follow these steps:

  1. Create the middleware class as shown in the code snippet above.

  2. Add the middleware to your Django settings. Open your settings.py file and locate the MIDDLEWARE setting. Add your middleware to the list, like this:

    # ...
    # ...

Make sure you define your onboarding start URL in your Django project's URL patterns, and it should match the URL checked in the middleware.

That's it! Your OnboardingMiddleware will now handle the redirection for users who haven't completed the onboarding process.


Middlewares is a powerful feature in Django that allows you to process requests and responses at a global level. The OnboardingMiddleware we've discussed is just one example of how a middleware can be used to add functionality to your Django project. You can create custom middlewares for various purposes, making your application more robust and user-friendly.

By understanding and leveraging a middleware, you can improve the user experience, add security measures, and handle cross-cutting concerns more efficiently in your Django application. So, go ahead and experiment with middleware to see how it can enhance your Django project. Happy coding!