如果用户已在Django中登录,如何从登录页面重定向?

时间:2016-12-01 02:38:09

标签: python django python-2.7

我试图这样做,当一个已登录的用户访问登录页面时,他们会重定向到他们的帐户页面。

我决定通过拥有自己的登录视图来执行此操作,该视图检查用户是否已登录并重定向(如果是)。然后,如果他们没有登录,则继续使用contrib登录视图。

问题是我需要能够指定contrib登录authentication_form和template_name。当我直接调用login()时,如何指定这些?

我正在运行Django版本1.10.3

这是我的代码......

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)

那么如何指定template_name& authentication_form?如果我是通过URL直接执行此操作,没有自定义登录视图,我会这样做...但我不能,因为我需要自定义登录视图。

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

1 个答案:

答案 0 :(得分:2)

不要使用基于功能的视图,使用基于类的视图LoginView

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

class LoginView(DefaultLoginView):
    redirect_authenticated_user = True

login = LoginView.as_view()

或者只需在urls.py中导入基于类的视图并传递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')