首页 > 解决方案 > NoReverseMatch at / Reverse for 'detail' with arguments '('',)' 未找到。尝试了 1 种模式:

问题描述

我正在逐步遵循 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/)views.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>

标签: pythondjango

解决方案


QuerySetlatest_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>

推荐阅读