【问题标题】:NoReverseMatch at / Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried:NoReverseMatch at / Reverse for 'detail' with arguments '('',)' 未找到。尝试了 1 种模式:
【发布时间】:2020-06-10 22:43:14
【问题描述】:

我正在逐步学习 django 教程,但无法找出我收到此错误的原因:

NoReverseMatch at /polls/

Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P<pk>[0-9]+)/$']

我的代码(基本上都是从教程复制的 - https://docs.djangoproject.com/en/3.0/intro/tutorial03/) 视图.py:

class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'

def get_queryset(self):
    """
    Return the last five published questions (not including those set to be
    published in the future).
    """
    return Question.objects.filter(
        pub_date__lte=timezone.now()
    ).order_by('-pub_date')[:5]

投票/urls.py

app_name = 'polls'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.DetailView.as_view(), name='detail'),
    path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

民意调查/index.html

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

【问题讨论】:

  • 上下文是latest_question_list 而不是question
  • 你的detailview功能!!!请

标签: python django


【解决方案1】:

QuerySet 在模板中作为latest_question_list 传递,这是Question 对象的集合,因此您应该迭代:

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

【讨论】:

    【解决方案2】:

    我也遇到过类似的失败。它在模板处迭代查询集。

    1. 我通过修复 URL regexp 来修复它;我换错了

    url(r'^courses/(?P&lt;slug&gt;[^/]+)/$', views.CategoryDetailView.as_view(), name='category-detail'),

    用的更合逻辑更正确

    url(r'^courses/(?P&lt;slug&gt;[^/]*)/$', views.CategoryDetailView.as_view(), name='category-detail'),

    这意味着slug 可以是空字符串(即courses// URL)。 (注意旧的+ 和新的*。)

    1. 您可能希望单独引入对courses// URL 的处理,而不是允许空的slug 变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-04
      • 1970-01-01
      • 1970-01-01
      • 2019-04-17
      • 2018-11-25
      • 2019-11-01
      • 2020-07-20
      相关资源
      最近更新 更多