这是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
,但是我从书中拿到了那个代码,所以我认为这没有错。
答案 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()
。