Django: Redirect logged in users from login page

django

Solution

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 (through `is_authenticated` attribute official documentation) 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),

Problem

I want to set up 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?

Original source