Dynamic login/logout URLs in Django
-
26-09-2019 - |
Question
I have an app that serves pages like this /stage/stagename. stagename is variable. The URL mappers just look for a [0-9A-Za-z]+ to fill that slot.
Now, because of my setup, My app will be rooted at /stage/stagename. I cannot change this (without massive changes to my setup which is too tedious right now and a last option).
I need to use django.contrib.auth
. The login and logout URLs can't be in my settings file since they will change depend on where my app is rooted (For one it might be /stage/foo/login and for the other, it might might /stage/bar/login).
How can I make the backend use such dynamic URLs?
I also have the issue that I need to pass the stagename parameter to the template which generates my URL. How can I do that?
Solution
If you can get redirect_to
into the context for your login template, then there is a mechanism you can use to choose vary the redirect URL.
In your login template, add an extra hidden input to the form
<input type="hidden" name="next" value="{% url redirect_to %}">
Now in your urls.py file, you can specify what input to use for the redirect:
url(r'^login/$',
auth_views.login,
{'template_name': 'registration/login.html',
'redirect_field_name': 'next'},
name='auth_login'),
If you do this, then you'll be redirected to different places depending on the value of redirect_to
.
You might be able to get redirect_to
into your context by having more than one named login url:
url(r'^login/$',
auth_views.login,
{'template_name': 'registration/login.html',
'redirect_field_name': 'next',
'extra_context': {'redirect_to': 'foo_url'}
},
name='foo_login'),
url(r'^login/$',
auth_views.login,
{'template_name': 'registration/login.html',
'redirect_field_name': 'next',
'extra_context': {'redirect_to': 'bar_url'}
},
name='bar_login'),
Or if you don't want to do that sort of thing, you could use something in the session instead:
<input type="hidden" name="next" value="{% url session.redirect_to %}">
Hope this helps, and apologies if there are typos in the code! The documentation for the auth login view is a bit hard to link to link. Go to that link and scroll up a bit!
OTHER TIPS
/stage/foo/login and for the other, it might might /stage/bar/login).
url( r'^stage/(?P<name>[^/]+)/login/$', some_view_function )
Might be what you're looking for.
However, you seem to have bigger problems than this. "massive changes to my setup which is too tedious" indicates more serious and fundamental problems.