[Django] Dynamic redirection after login
Here’s how to redirect to the login page in django, making it go to a certain view (by name) after a successful login:
login_url = '%s?next=%s' % (reverse('acct_login'), reverse('jumplog_index'))
return HttpResponseRedirect(login_url)
Notes:
- acct_login is django’s view name for the login page (double check this, as it might change in future django versions);
- jumplog_index is the target view where I want the user to go after successfully logging in.
UPDATE: An alternative, much more awesome, is to use the @login_required decorator on the view you want login to be required. Like so:
@login_required def index(request): # Your code here
The decorator can be imported from this module:
from django.contrib.auth.decorators import login_required
I guess the first dirtier method can be used when you want to do something more custom, like sending some data to the login view, or something like that
Thanks for the tip, Steve
Related:
- Django: Reverse HTTP redirect with parameters Here’s how to, from a view, redirect to another URL...
- Django in AppEngine It’s as easy as following this article: http://code.google.com/appengine/articles/django.html. A couple...
Categorised as: code snipplets, software development, tips
Ha, thanks.
Not a genius, that’s all down to the Django guys. But yeh, your method would come in handy if you need to do some more custom stuff. The acct_login tip is handy
Couldn’t you just use the @login_required decorator?
If I’m not mistaken, this handles all the ?next jiggery-pokery for you.
I’ll give it a try. If it works it’s much better indeed
You’re a genius. It works. Much, much better