我正在关注 Django 教程,并已完成教程 3 中的解耦 URLConfs。在此步骤之前,一切正常。现在,当我执行删除模板中的硬编码 URL 的最后一步时,它正在发生变化
<li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>
到
<li><a href="{% url 'polls.views.detail' poll.id %}">{{ poll.question }}</a></li>
我收到此错误:
NoReverseMatch at /polls/
Reverse for ''polls.views.detail'' with arguments '(1,)' and keyword arguments '{}' not found.
Request Method: GET
Request URL: http://localhost:8000/polls/
Django Version: 1.4
Exception Type: NoReverseMatch
Exception Value:
Reverse for ''polls.views.detail'' with arguments '(1,)' and keyword arguments '{}' not found.
Exception Location: e:\Django\development\tools\PortablePython\PortablePython2.7.3.1\App\lib\site-packages\django\template\defaulttags.py in render, line 424
Python Executable: e:\Django\development\tools\PortablePython\PortablePython2.7.3.1\App\python.exe
我的views.py
样子是这样的:
from django.shortcuts import render_to_response, get_object_or_404
from polls.models import Poll
def index(request):
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
def detail(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('polls/detail.html', {'poll': p})
def results(request, poll_id):
return HttpResponse("You're looking at the results of poll %s." % poll_id)
def vote(request, poll_id):
return HttpResponse("You're voting on poll %s." % poll_id)
我的项目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)),
)
polls/urls.py
看起来像这样:
from django.conf.urls import patterns, include, url
urlpatterns = patterns('polls.views',
url(r'^$', 'index'),
url(r'^(?P<poll_id>\d+)/$', 'detail'),
url(r'^(?P<poll_id>\d+)/results/$', 'results'),
url(r'^(?P<poll_id>\d+)/vote/$', 'vote'),
)
显然我错过了一些东西,但我现在已经完成了第 3 部分几次,无法弄清楚我错过了什么。我需要纠正什么才能正确解耦这些 URL?