LogoutView中的template_name在django2.1 python3.7上不起作用

时间:2018-09-04 07:53:41

标签: django-templates python-3.7 django-2.1

以下是django.contrib.auth.views.LogoutViews中的默认设置,

template_name = 'registration/logged_out.html'

我这样配置我应用的urls.py:

from django.urls import path
from . import views

from django.conf import settings

from django.contrib.auth.views import LoginView, LogoutView

app_name = 'account'
urlpatterns = [
    #path("login/", views.user_login, name="user_login"),
    path("login/", LoginView.as_view(), name="user_login"),
    path("nlogin/", LoginView.as_view(), {"template_name":"account/login.html"}),
    path("logout/", LogoutView.as_view(), name="user_logout"),
    path("logoutt/", LogoutView.as_view(), {"template_name":"account/logout.html"}),
]

“ template_name”:“ account / login.html”正常工作,但是“ template_name”:“ account / logout.html”似乎没有什么区别,我的代码有什么问题?

2 个答案:

答案 0 :(得分:0)

使用基于基于类的变体时,您可以通过.as_view(即所谓的**initkwargs)方法将设置传递给视图:

from django.urls import path
from . import views

from django.conf import settings

from django.contrib.auth.views import LoginView, LogoutView

app_name = 'account'

urlpatterns = [
    #path("login/", views.user_login, name="user_login"),
    path("login/", LoginView.as_view(), name="user_login"),
    path("nlogin/", LoginView.as_view(template_name='account/login.html')),
    path("logout/", LogoutView.as_view(), name="user_logout"),
    path("logoutt/", LogoutView.as_view(template_name='account/logout.html')),
]

否则,参数将以self.kwargs结尾,并且基于类的视图不会检查这些参数。

documentation on the LoginView [Django-doc]提到了这一点以及可以作为**initkwargs传递的参数列表。

答案 1 :(得分:0)

根据Willem Van Onsem's advice,我发现关键问题是我混合了两种方式的urlpattern,如下所示:

  1. url()和urls.py中的正则表达式类型(我在django 1.10.1教程中了解到)

    from django.conf.urls import url
    from django.contrib.auth import views
    urlpatterns = [
        url(r"^login/$", views.login, {"template_name"="account/login.html"}, name='user_login'),
    ]
    
  2. path()输入urls.py(django 2.1文档)

    from django.urls import path
    from django.contrib.auth.views import LoginView
    urlpatterns = [
        path("login/", LoginView.as_view(template_name="account/login.html"),name="user_login"),
    ]
    

很明显,需要注意两个主要区别:

  1. 从django.conf.urls导入URL,但直接从django.urls导入路径,并且django 2.0中的路径类型是新的,路径似乎更简单
  2. 在django 2.1中,LoginView和LogoutView设置通过as_view()传递,与旧表达式 views.login,{“ template_name” =“ account / login.html”} 比较简单也是