Henry Li
Henry Li

Reputation: 3

Django: NoReverseMatch in html

I am always getting this error in detail.html

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

the detail.html is

<h1>{{ question.question_text }}</h1>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'detail' question.id%} " method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
    <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
    <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>

and my polls.url.py is

urlpatterns = [

    path('', views.index, name='index'),

    path('<int:question_id>/', views.detail, name='detail'),

    path('<int:question_id>/results/', views.results, name='results'),

    path('<int:question_id>/vote/', views.vote, name='vote'),
]

The issue is that I have a similar code <a href = "{% url 'vote' question.id %}"> in index.html, it will work.

The project directory is here directory

I am so sorry, I found that there is a bug in my views.py

def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    choice_set = question.choice_set.all();
    return render(request, 'polls/detail.html', {'question': choice_set})

The html is asking for Question but I am passing a choice_set(Question is Choice's foreign key). I am not sure how it led to a NoReverseMatch error. Again, thanks for all your help.

Upvotes: 0

Views: 261

Answers (1)

sax
sax

Reputation: 3806

as per you url.py you expect a url <int:question_id>/vote/ but instead of int you are passing an empty string. ... arguments '('',) so urlresolver does not find any urls that match <string:question_id>/vote/.

Not sure, but is possible that you are using this template with an "unsave" question object so it does not have id

Upvotes: 3

Related Questions