Skip to content Skip to sidebar Skip to footer

Django Dynamic Urlpatterns

I'm building a simple web application with Django. My users are separated into multiple groups, for example Group A, Group B, etc. What I want to do is to dynamically update urlpat

Solution 1:

I think this is neither possible nor desirable. You should place such logic in the view. Make both land in the same view and redirect or simply put together different content in the view based on the user's group affiliation.


Solution 2:

It's not a good idea to change urlpatterns dynamically, but you could create two url confs mysite/groupA_root_urls.py and mysite/groupB_root_urls.py.

You can then write a middleware that sets the request.urlconf attribute to either 'mysite.groupA_root_urls' 'mysite.groupA_root_urls'.

Django will then use that urlconf instead of the conf from the ROOT_URLCONF setting.


Solution 3:

URLs are not loaded dynamically for every user, they are parsed and loaded on application startup, so you cannot put per-request logic in there. In general, this logic should be handled in your view.

That said, you can simulate this behavior using custom middleware. Make a middleware class, write process_view() method to check your URL and if it one you are interested in, find and run the view function yourself and return the HttpResponse. Make sure your middleware is the last in the list, so every other middleware gets a chance to run before yours does. Mind you that this would fall under the "ugly hack" category in any serious project :)

Here is a link to relevant docs https://docs.djangoproject.com/en/1.9/topics/http/middleware/#process-view


Post a Comment for "Django Dynamic Urlpatterns"