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. 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.
This is what Django does anyway.
Check for a session and redirect to a login properly, using Django’s already provided functions.
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
reversefunction — do not code the URL anywhere in your applications. Ever.