请求/响应中间件中的Django错误-TypeError:__init __()接受1个位置参数,但给出了2个

时间:2018-08-21 07:26:27

标签: python django

我还是Django的新手,似乎无法解决此错误(我在这里读过类似的文章没有运气)。 urls.py中的代码粘贴如下:

from django.conf.urls import include, url
from django.contrib import admin
# Add this import
from django.contrib.auth import views
from log.forms import LoginForm

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include(('dashboard.urls', "dashboard"), namespace='dashboard')),
    url(r'^login/$', views.LoginView, {'template_name': 'login.html', 'authentication_form': LoginForm}, name='login'),
    url(r'^logout/$', views.LogoutView, {'next_page': '/'}),
]

完整跟踪如下:

Internal Server Error: /login/
Traceback (most recent call last):
  File "C:\Python36-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Python36-32\lib\site-packages\django\core\handlers\base.py", line 127, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Python36-32\lib\site-packages\django\core\handlers\base.py", line 125, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
TypeError: __init__() takes 1 positional argument but 2 were given
[21/Aug/2018 00:20:27] "GET /login/?next=/ HTTP/1.1" 500 64213

关于如何解决此问题的任何想法?还是什么可能导致此错误?

1 个答案:

答案 0 :(得分:1)

简而言之:您需要使用 .as_view() 将基于类的视图“转换”为可以在{{ 1}}。

LoginView [Django-doc]LogoutView [Django-doc]是基于类的视图,为了使其在urls.py中可调用,您需要使用{{1} }:

urls.py

基于类的视图包含充当包装器的功能,并且每次初始化时都如此。如果直接使用as_view,则将调用from django.conf.urls import include, url from django.contrib import admin # Add this import from django.contrib.auth import views from log.forms import LoginForm urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include(('dashboard.urls', "dashboard"), namespace='dashboard')), url(r'^login/$', views.LoginView.as_view(), {'template_name': 'login.html', 'authentication_form': LoginForm}, name='login'), url(r'^logout/$', views.LogoutView.as_view(), {'next_page': '/'}), ]类的构造函数。尽管有一些额外的逻辑,但有可能返回一个LoginView,但它不是很优雅(构造LoginView时您不会期望HttpResponse),而且还会返回使视图的子类化(这是此类基于类的视图可以节省大量工作的原因之一)非常麻烦。