Non-global middleware in Django

hekevintran picture hekevintran · May 26, 2010 · Viewed 15.5k times · Source

In Django there is a settings file that defines the middleware to be run on each request. This middleware setting is global. Is there a way to specify a set of middleware on a per-view basis? I want to have specific urls use a set of middleware different from the global set.

Answer

Ned Batchelder picture Ned Batchelder · May 27, 2010

You want decorator_from_middleware.

from django.utils.decorators import decorator_from_middleware

@decorator_from_middleware(MyMiddleware)
def view_function(request):
    #blah blah

It doesn't apply to URLs, but it works per-view, so you can have fine-grained control over its effect.