我正在关注Django教程并在教程3中将其发送到Decoupling the 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'),
)
显然我错过了一些东西,但我现在已经过了几次,并且无法弄清楚我错过了什么。我需要纠正什么才能正确地分离这些网址?
答案 0 :(得分:4)
这是版本问题。您已经以某种方式找到了Django开发版本的链接,而您正在使用1.4版本。自发布以来发生变化的一件事是,模板中的URL名称不需要引号,但现在却可以。这就是错误消息在两组引号中具有URL名称的原因。
您应该使用this version of the tutorial来匹配您拥有的Django版本。 (您可以安装开发版本,但不建议这样做 - 坚持发布。)