I want to setup my site so that if a user hits the /login page and they are already logged in, it will redirect them to the homepage. If they are not logged in then it will display normally. How can I do this since the login code is built into Django?
+5
A:
I'm assuming you're currently using the built-in login view, with
(r'^accounts/login/$', 'django.contrib.auth.views.login'),
or something similar in your urls.
You can write your own login view that wraps the default one. It will check if the user is already logged in and redirect if he is, and use the default view otherwise.
something like:
from django.contrib.auth.views import login
def custom_login(request):
if request.user.is_authenticated():
return HttpResponseRedirect(...)
else:
return login(request)
and of course change your urls accordingly:
(r'^accounts/login/$', custom_login),
Ofri Raviv
2010-02-23 18:28:10
You should declare `custom_login` with a second argument `**kwargs` so that it passes all arguments you don't care to the built-in `login` view.
Török Gábor
2010-06-18 07:41:32
A:
All you have to do is set the "root" url to the homepage view. Since the homepage view is already restricted for logged on users, it'll automatically redirect anonymous users to the login page.
Kepp the url as it is. And add something like:
(r'^$', 'my_project.my_app.views.homepage'),
Luiz C.
2010-02-23 20:26:17
Please read the OP carefully. The question is about how to redirect *logged in* users from the login page if they were already authenticated. The built-in `login` view does not cover this case.
Török Gábor
2010-06-18 07:43:37
The approach I suggest works just as well. All he wants is for logged in users to skip the login page. My approach suggests that the main (root) page is the home page. Since the home page is login restricted, anonymous users will be redirected to the login page. I've use this approach before. Don't mark my solution down because you don't understand it.
Luiz C.
2010-06-22 16:47:12