Django教程:通用视图。属性错误

时间:2012-09-06 16:03:22

标签: python django django-generic-views

我正处于this教程的最后一部分。

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)),
)

2 个答案:

答案 0 :(得分: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 。另请注意,本教程是正确的,并且您发布了正确的代码(来自教程。)

答案 1 :(得分:0)

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