【问题标题】:Django tutorial part 3 - NoReverseMatch at /polls/Django 教程第 3 部分 - /polls/ 中的 NoReverseMatch
【发布时间】:2016-12-24 04:02:48
【问题描述】:

我一直关注Django tutorial part 3,当我尝试查看http://localhost:8000/polls/ 时出现以下错误:

**Reverse for 'detail' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'polls/(?P<question_id>[0-9]+)/$']**

我的文件如下:

mysite/urls.py:

from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
    url(r'^polls/', include('polls.urls', namespace="polls")),
    url(r'^admin/', admin.site.urls),
]

投票/urls.py:

from django.conf.urls import url
from . import views
app_name = 'polls'
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
    url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
    url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]

民意调查/detail.html:

<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>

投票/模板/投票/index.html:

<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>

这个错误是什么意思?

如何调试它?

您能提出解决办法吗?

注意我已经看到并尝试了类似问题的答案:

NoReverseMatch at /polls/ (django tutorial) Django 1.8.2 -- Tutorial Chapter 3 -- Error: NoReverseMatch at /polls/ -- Python 3.4.3 NoReverseMatch - Django 1.7 Beginners tutorial Django: Reverse for 'detail' with arguments '('',)' and keyword arguments '{}' not found https://groups.google.com/forum/#!msg/django-users/etSR78dgKBo/euSYcSyMCgAJ NoReverseMatch at /polls/ (django tutorial) https://www.reddit.com/r/django/comments/3d43gb/noreversematch_at_polls1results_in_django/

编辑,我最初错过了以下问题。它的优秀答案部分回答了我的问题(如何调试),但没有涵盖我的具体问题。

What is a NoReverseMatch error, and how do I fix it?

【问题讨论】:

  • 这个具体案例的实际问题是question.id是空的
  • @Sayse 谢谢,这是否意味着错误是意料之中的,我不应该看localhost:8000/polls
  • 是的,因为question.id 是空的,你可以看到你有一个空字符串参数`并且你没有一个不匹配的url。所以你需要弄清楚为什么那个 id 不见了
  • @Sayse 很公平,谢谢。

标签: python html django python-2.7


【解决方案1】:

这就是问题所在:

polls/templates/polls/index.html 应该是:

{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

我无意中将整个文件替换为以下行,而不是仅更新相关行(暗示 here):

<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>

正如@Sayse 在 cmets 中所说,这意味着 question.id 为空,从而导致错误。

【讨论】:

    猜你喜欢
    • 2016-01-14
    • 2018-11-02
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    • 2017-08-21
    相关资源
    最近更新 更多