23

I want to use some middleware I wrote across the whole of my site (large # of pages, so I chose not to use decorators as I wanted to use the code for all pages). Only issue is that I don't want to use the middleware for the admin code, and it seems to be active on them.

Is there any way I can configure the settings.py or urls.py perhaps, or maybe something in the code to prevent it from executing on pages in the admin system?

Any help much appreciated,

Cheers

Paul


The main reason I wanted to do this was down to using an XML parser in the middleware which was messing up non-XML downloads. I have put some additional code for detecting if the code is XML and not trying to parse anything that it shouldn't.

For other middleware where this wouldn't be convenient, I'll probably use the method piquadrat outlines above, or maybe just use a view decorator - Cheers piquadrat!

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
user127032
  • 231
  • 1
  • 2
  • 3

3 Answers3

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.

viam0Zah
  • 25,949
  • 8
  • 77
  • 100
Issac Kelly
  • 6,309
  • 6
  • 43
  • 50
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
Benjamin Wohlwend
  • 30,958
  • 11
  • 90
  • 100
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)
Javier Buzzi
  • 6,296
  • 36
  • 50