python - 请求/响应中间件中的 Django 错误 - TypeError : __init__() takes 1 positional argument but 2 were given

标签 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

关于如何解决这个问题有什么想法吗?或者什么可能导致此错误?

最佳答案

简而言之:您需要使用 .as_view() 将基于类的 View “转换”为可在 urls.py 中使用的 View .

LoginView [Django-doc] LogoutView [Django-doc]基于类的 View ,以便使它们可以在 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<b>.as_view()</b>, {'template_name': 'login.html', 'authentication_form': LoginForm}, name='login'),
    url(r'^logout/$', views.LogoutView<b>.as_view()</b>, {'next_page': '/'}),
]

基于类的 View 包含充当包装器的函数,并且每次初始化实例。如果您使用 LoginView直接调用 LoginView 的构造函数类(class)。尽管有一些额外的逻辑,但可以返回 HttpResponse ,它不是很优雅(当你构造 HttpResponse 时,你不会期望 LoginView ),此外它还会对 View 进行子类化(这就是为什么这种基于类的 View 可以节省大量资源的原因之一)工作)很麻烦。

关于python - 请求/响应中间件中的 Django 错误 - TypeError : __init__() takes 1 positional argument but 2 were given,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51943610/

相关文章:

Django:如何使用 settings.AUTH_USER_MODEL 执行查询?

django - 模块 "django.core.context_processors"未定义 "auth"可调用请求处理器

python - 如何解释 Keras 中 model.predict() 的输出

python - pyspark.sql.types.Row 列表

python - 是否可以在 transform.compose 中使用非 pytorch 增强

django - 在 Django 中以编程方式执行嵌套 GET 请求

python - Visual Studio 2019 找不到 python 测试(pytest 或 unittest)

python : running Excel macro with python

python - 使用 ngram 范围进行标记化

python - 如何在 Django 中获取带有注释的每天帖子数量?