Django
按照官方文档,我正在创建一个 Django 应用程序(与文档页面中的投票应用程序相同)。使用基于类的 View 时,出现错误。我对基于类的 View 了解不多,例如,有人可以解释一下,基于类的 View 与普通 View 有什么区别?
这是我的代码:
class DetailView(generic.DetailView):
model = Poll
template_name = 'polls/details.html'
def get_queryset(self):
def detail(request, poll_id):
try:
poll = Poll.objects.get(pk=poll_id)
except Poll.DoesNotExist:
raise Http404
return render(request, 'polls/details.html', {'poll': poll})
*********************Error ********************
TypeError at /polls/2/results/
as_view() takes exactly 1 argument (3 given)
Request Method: GET
Request URL: <app-path>/polls/2/results/
Django Version: 1.5.1
Exception Type: TypeError
Exception Value:
as_view() takes exactly 1 argument (3 given)
*****the url***
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view, name='detail')
最佳答案
as_view
应该被调用,而不是被引用,根据 docs ,您的网址应如下所示:
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail')
注意括号的用法。
另外,您应该调用您的类 PollDetailView
以避免代码阅读器混淆。
此外,您定义的detail()
方法根本不会被调用。所以你根本不应该定义它。此外,暂时不要使用 get_queryset()
方法,先尝试让基本 View 工作。
关于python - Django 基于类的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17469461/