Question

I would like to conditionally route urls in my django application based upon the contents of the http request, similar to this:

if request.user.is_authenticated() and request.user.is_staff():
       #provide a specific set of urls
elif request.user.is_authenticated():
       #provide alternative urls
else
       #provide default urls

I would like to do this inside the url dispatcher inside my application, as I would like certain urls to be completely unavailable to a user if they are not logged in. I feel that doing it this way would be much cleaner than pointing to views to determine what is rendered. Has anyone ever done this? Is this even possible in Django? Thanks

Was it helpful?

Solution

This is not possible. The urls file isn't read each time a request comes in. It runs when you start up an instance of django before requests are being handled.

The suggestion made by user995394 would be the way I would handle it.

Digging a bit deeper if you did want to do this. You could specify a request middleware.

class FooMiddleware(object):
    def process_request(self, request):
        if request.user.is_authenticated():
            request.urlconf = 'myproject.authed_urls2'

I tested the above middleware in a django project. When I login the alternate file is handled for that request while in another window a non authenticated user is still using the original url conf.

Still though, I recommend using decorators on your views. If you are concerned with people discovering urls that only staff should know about you can have your auth required decorator respond with NotFound instead of NotAuthorized

OTHER TIPS

This might be possible either with a custom middleware (in the process_request part) or by monkey patching core.handlers.BaseHandler.get_response(), but really using decorators (which can be done in your urls.py files too) is the sane way to go.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top