fro*_*oob 15 python django django-templates django-views
我正在按照官方教程学习Django并使用1.5.
我有这个链接作为我的索引模板的一部分,这是正常工作:
<li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>
但是,这是硬编码的,教程建议更好的方法是使用:
<li><a href="{% url 'detail' poll.id %}">{{ poll.question }}</a></li>
这样你在处理大量模板时会更好,你必须对网址进行更改.
由于我进行了上述更改,因此在运行应用时出现以下错误:
Exception Type: NoReverseMatch
Exception Value:    Reverse for 'detail' with arguments '('',)' and keyword arguments '{}' not found.
我的urls.py看起来像这样:
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
    url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'),
   url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),                     
)
views.py看起来像这样:
from django.shortcuts import render, get_object_or_404
from django.http import Http404
from polls.models import Poll
def index(request):
    latest_poll_list = Poll.objects.order_by('-pub_date')[:5]
    context = {'latest_poll_list': latest_poll_list}
    return render(request, 'polls/index.html', context)
def detail(request, poll_id):
    poll = get_object_or_404(Poll, pk = poll_id)
    return render(request, 'polls/detail.html', {'poll': poll})
我的index.html模板如下所示:
{% if latest_poll_list %}
    <ul>
    {% for poll in latest_poll_list %}
        <li><a href="{% url 'polls:detail' poll_id %}">{{ poll.question }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p> No polls are available.</p>
{% endif %}
通常我可以很容易地读出错误来自哪里并处理它但在这种情况下我无法找出错误的原因因此我无法继续我的学习.任何帮助将不胜感激.
dmv*_*nna 10
我的错误是错字detail.html:
<form action={% url 'polls:vote' polls.id %}" method="post">
本来应该
<form action={% url 'polls:vote' poll.id %}" method="post">
我花了一段时间才意识到django追溯页面始终指向相关的代码行.:$