NoReverseMatch at / Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried:

Viewed 5234

I'm following django tutorial step by step, but can't to find out why I'm getting this error:

NoReverseMatch at /polls/

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

My code(basically everything copied from tutorial - 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]

polls/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'),
]

polls/index.html

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

The QuerySet is passed as latest_question_list in the template, and this is a collection of Question objects, you thus should iterate:

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

I had a similar failure. And everywhere it was iterating querysets at the templates.

  1. I fixed it by fixing the URL regexp; I replaced the wrong

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

with the more logical and correct

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

which means that the slug can be empty string (i.e. courses// URL). (Note the old + and the new *.)

  1. You might wish to introduce the handling for courses// URL separately instead of allowing for empty slug variable.
Related