Django TypeError:__init __()接受1个位置参数,但给出了2个

时间:2020-07-26 04:29:35

标签: python django

这是views.py中的班级代码:

class Ask(CreateView):
    template_name = 'f/ask.html'
    form_class = QuestionForm
    success_url = '/f/ask/'

    def get_context_data(self, **kwargs):
        content = super().get_context_data(**kwargs)
        return content

这是我的urls.py代码

from django.urls import path, register_converter
from . import views, converter

register_converter(converter.HexConverter, 'hex')

urlpatterns = [
    path('', views.QuestionView),
    path('ask/', views.Ask),
    path('<hex:pk>/', views.QuestionCurrent, name='question_current'),
]

上面写着__init__() takes 1 positional argument but 2 were given,但是我从书中拿到了那个代码,所以我认为这没有错。

1 个答案:

答案 0 :(得分:3)

.as_view()添加到urls.py 中的路径(因为它们是基于class的路径)

发件人:

from django.urls import path, register_converter
from . import views, converter

register_converter(converter.HexConverter, 'hex')

urlpatterns = [
    path('', views.QuestionView),
    path('ask/', views.Ask),
    path('<hex:pk>/', views.QuestionCurrent, name='question_current'),
]

收件人:

from django.urls import path, register_converter
from . import views, converter

register_converter(converter.HexConverter, 'hex')

urlpatterns = [
    path('', views.QuestionView.as_view()),
    path('ask/', views.Ask.as_view()),
    path('<hex:pk>/', views.QuestionCurrent.as_view(), name='question_current'),
]

从文档中:

classmethod as_view(**initkwargs)

返回接受请求并返回响应的可调用视图:

response = MyView.as_view()(request)

返回的视图具有view_class和view_initkwargs属性。

在请求/响应周期中调用视图时,setup()方法将HttpRequest分配给视图的请求属性,并将从URL模式捕获的所有位置和/或关键字参数分配给args和kwargs属性。然后调用dispatch()