views:

255

answers:

3

Hi all,

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

+4  A: 

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
piquadrat
A: 

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!

+2  A: 

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.

Issac Kelly
Nice tip for flexibility.
Török Gábor