Ricky Ricky - 8 days ago 5
Python Question

How do I redirect away from the login page, if the user is already logged in in Django?

I'm trying to make it so when a user that is ALREADY logged in visits the login page, they are redirect to their account page.

I decided to do this by having my own Login View, that checks if the user is logged in and redirects if they are. Then if they are not logged in, it continues using the contrib login view.

The issue is that I need to be able to specify the contrib login authentication_form and template_name. How do I specify those when I'm calling login() directly?

I'm running Django version 1.10.3

Here's my code...

urls.py

from django.conf.urls import include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from Account.views import RenderLoginPage
from django.contrib.auth.views import logout

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login/$', RenderLoginPage, name='login'),
url(r'^logout/$', logout, {'next_page': '/login'}, name='logout')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


views.py

from django.shortcuts import redirect
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import login
from forms import LoginForm

def RenderLoginPage(request):
if request.user.is_authenticated():
return redirect(reverse("myaccount"))
else:
return login(request)


So how do I specify the template_name & authentication_form? If I was doing this directly through URLs, without a custom Login View I would do this... but I can't because I need the custom login view.

url(r'^login/$', login, {'template_name': 'login.html', 'authentication_form': LoginForm}, name='login'),

Answer

Do not use function based view, use class based view LoginView:

from django.contrib.auth.views import LoginView as DefaultLoginView

class LoginView(DefaultLoginView):
    redirect_authenticated_user = True

login = LoginView.as_view()

Or simply import the class based view in urls.py and pass redirect_authenticated_user=True:

from django.contrib.auth.views import LoginView

url(r'^login/$', LoginView.as_view(), 
    {'template_name': 'login.html', 'authentication_form': LoginForm, 'redirect_authenticated_user': True},
    name='login')