15

我在教程的最后一部分。

from django.conf.urls import patterns, include, url
from django.views.generic import DetailView, ListView
from polls.models import Poll

urlpatterns = patterns('',
    url(r'^$',
        ListView.as_view(
            queryset=Poll.objects.order_by('-pub_date')[:5],
            context_object_name='latest_poll_list',
            template_name='polls/index.html')),
    url(r'^(?P<pk>\d+)/$',
        DetailView.as_view(
            model=Poll,
            template_name='polls/detail.html')),
    url(r'^(?P<pk>\d+)/results/$',
        DetailView.as_view(
            model=Poll,
            template_name='polls/results.html'),
        name='poll_results'),
    url(r'^(?P<poll_id>\d+)/vote/$', 'polls.views.vote'),
)

ListView 有效,但是当我使用 DetailView 访问 url 时,我得到了。

AttributeError at /polls/2/
Generic detail view DetailView must be called with either an object pk or a slug.
Request Method: GET
Request URL:    http://127.0.0.1:8000/polls/2/
Django Version: 1.4.1
Exception Type: AttributeError
Exception Value:    
Generic detail view DetailView must be called with either an object pk or a slug.
Exception Location: /home/yasith/coding/django/django-tutorial/lib/python2.7/site-packages/django/views/generic/detail.py in get_object, line 46
Python Executable:  /home/yasith/coding/django/django-tutorial/bin/python2
Python Version: 2.7.3

我不确定我做错了什么。任何帮助,将不胜感激。

编辑:添加主 urls.py

from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^polls/', include('polls.urls')),
    url(r'^admin/', include(admin.site.urls)),
)
4

2 回答 2

40

我认为您在上面发布的代码不是您磁盘上的代码。

我遇到了同样的问题,但后来我仔细查看了我的代码和教程。我在代码中使用的正则表达式与教程不同。

这是我的代码:

 url(r'^(?P<poll_id>\d+)/$',-$                                               
 url(r'^(?P<poll_id>\d+)/results/$',-$                                       

这是正确的核心:

 url(r'^(?P<pk>\d+)/$',-$                                               
 url(r'^(?P<pk>\d+)/results/$',-$                                       

请注意, *poll_id* 在本教程的前面部分中,但通用视图需要pk。另请注意,教程是正确的,并且您发布了正确的代码(来自教程。)

于 2012-10-15T19:32:19.117 回答
0

仔细查看他们提到的将 urlpatterns 更改为使用 primarykey 而不是 question_id 的教程。

于 2014-05-26T18:01:55.530 回答