Django:使用参数'('',)'和关键字参数'{}'未找到'detail'的反转 [英] Django: Reverse for 'detail' with arguments '('',)' and keyword arguments '{}' not found
问题描述
我正在按照官方教程学习 Django 并使用 1.5.
I'm following the official tutorial to learn Django and using 1.5.
我将此链接作为索引模板的一部分,它运行良好:
I had this link as part of my index template, which was working fine:
<li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>
然而,这是硬编码的,教程建议更好的方法是使用:
however, this is hardcoded and the tutorial suggested a better way was to use:
<li><a href="{% url 'detail' poll.id %}">{{ poll.question }}</a></li>
这样您就可以更好地处理大量模板并且您必须更改网址.
so that you'll be better of when dealing with huge number of templates and u have to make changes to the url.
由于我进行了上述更改,因此在运行应用程序时出现以下错误:
Since I made the above change I get the following errors when I run the app:
Exception Type: NoReverseMatch
Exception Value: Reverse for 'detail' with arguments '('',)' and keyword arguments '{}' not found.
我的 urls.py 看起来像这样:
My urls.py looks like this:
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 看起来像这样:
views.py looks like this:
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 模板如下所示:
my index.html template looks like this:
{% 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 %}
通常我可以轻松地读取错误的来源并进行处理,但在这种情况下,我无法发现错误的原因,因此我无法继续我的研究.任何帮助将不胜感激.
Usually I could easily read where the error is coming from and deal with it but in this case I can't spot the cause of the error hence I'm unable to progress with my study. Any help will be greatly appreciated.
推荐答案
在你的 index.html
中,你给了 poll_id
作为参数,但这只是参数的名称将在 detail
函数中;它没有在您的模板中定义.您想要调用函数的实际值可能是 poll.id
.
In your index.html
you gave poll_id
as an argument, but that's just the name the argument will have within the detail
function; it is not defined in your template. The actual value you want to call the function with is probably poll.id
.
这篇关于Django:使用参数'('',)'和关键字参数'{}'未找到'detail'的反转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!