Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 267
user127032 Avatar asked Jun 22 '09 16:06

user127032


People also ask

What is Get_response in Django middleware?

get_response(request) # Code to be executed for each request/response after # the view is called. return response. The get_response callable provided by Django might be the actual view (if this is the last listed middleware) or it might be the next middleware in the chain.

Is Django admin used in production?

Django's Admin is amazing. A built-in and fully functional interface that quickly gets in and allows data entry is priceless. Developers can focus on building additional functionality instead of creating dummy interfaces to interact with the database.

Can I use Django admin as frontend?

Django's Docs clearly state that Django Admin is not made for frontend work.

What is GZipMiddleware?

gzip. GZipMiddleware compresses content for browsers that understand GZip compression (all modern browsers). This middleware should be placed before any other middleware that need to read or write the response body so that compression happens afterward.


2 Answers

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.

like image 161
Issac Kelly Avatar answered Sep 21 '22 08:09

Issac Kelly


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
like image 24
Benjamin Wohlwend Avatar answered Sep 18 '22 08:09

Benjamin Wohlwend