[Django]-Conditional Django Middleware (or how to exclude the Admin System)

41👍

A general way would be (based on piquadrat’s answer)

def process_request(self, request):
    if request.path.startswith(reverse('admin:index')):
        return None
    # rest of method

This way if someone changes /admin/ to /django_admin/ you are still covered.

10👍

You could check the path in process_request (and any other process_*-methods in your middleware)

def process_request(self, request):
    if request.path.startswith('/admin/'):
        return None
    # rest of method

def process_response(self, request, response):
    if request.path.startswith('/admin/'):
        return response
    # rest of method

1👍

You don’t need to muck around with paths.

If you want to exclude a single middleware from a view, you must first import that middleware and do:

from django.utils.decorators import decorator_from_middleware

from your.path.middlewares import MiddleWareYouWantToExclude

@decorator_from_middleware(MiddleWareYouWantToExclude)
def your_view(request):
    ....

If you want to exclude ALL middleware regardless of what they are/do, do this:

from django.conf import settings
from django.utils.module_loading import import_string
from django.utils.decorators import decorator_from_middleware

def your_view(request):
    ...

# loop over ALL the active middleware used by the app, import them
# and add them to the `decorator_from_middleware` decorator recursively
for m in [import_string(s) for s in settings.MIDDLEWARE]:
    your_view = decorator_from_middleware(m)(your_view)

Leave a comment