Conditional login redirect in Django
I know about LOGIN_REDIRECT_URL
and I know about
<form action="?next={{ next|default:"/foo" }}" method="post">
in django-registration's login.html template. Here's what I want to happen:
If a user logs in from the homepage, redirect them to a URL that contains their username (/lists/[username]).
If a user logs in from any other page, return them to the page they were viewing.
The way twitter.com handles this is to simply make the homepage go away for logged in users. I would consider doing that, and it would be pretty easy to solve, but my homepage still has useful stuff on it and I'm not sure I want it to go away for authenticated users. I'd rather redirect them.
I was thinking I could do a conditional in settings.py where LOGIN_REDIRECT_URL
is referenced, but the request object is not available in settings (so I can't access request.user.username to build the redirect). And obviously, I can't do it in django-registration's "default" parameter in the template because the username isn't known before login.
What's the correct/best way to solve this? Thanks.
Update: Based on S.开发者_StackOverflow Lott's suggestion below, this is what I ended up using (in the homepage view):
if request.user.is_authenticated() and not request.session.get('homepage_redir'):
request.session['homepage_redir'] = True
return HttpResponseRedirect(reverse('list_view',args=[request.user.username]))
On the first login from homepage, the user is redirected to their personal page and a session variable is set. On subsequent requests for the homepage, the redirect does not occur (because the session var is detected). Code for redirecting logins from any other page is not affected.
If a user logs in from any other page, return them to the page they were viewing.
This is what Django does anyway.
Check for a session and redirect to a login properly, using Django's already provided functions.
If a user logs in from the homepage, redirect them to a URL that contains their username (/lists/[username]).
This is what view functions are for.
If the request session is empty, they just logged in. Set a flag in the session and return a redirect to the desired page. Be sure to use the reverse
function -- do not code the URL anywhere in your applications. Ever.
Caveat: this is hackish.
Do you mind doing two redirects? This way your LOGIN_REDIRECT_URL
can be a view that identifies the logged in user and redirects the request to the appropriate home page for the user (/lists/username/
)
This will cost you two redirects instead of the usual one. First, post login to the view, next from the view to the home page.
精彩评论