Conditional Django Middleware (or how to exclude the Admin System) Conditional Django Middleware (or how to exclude the Admin System) python python

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


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.


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 methoddef process_response(self, request, response):    if request.path.startswith('/admin/'):        return response    # rest of method


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!