Soe Phyu Phyu Htun
Soe Phyu Phyu Htun

Reputation: 1

Django Documentation Tutorial NoReverseMatch at /polls/1/results/

I get the following error:

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

In polls.views

def vote(request, question_id):
    question = get_object_or_404( Questions, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render(request, 'polls/detail.html',{'question':question, 'error_message':"You didn't select a choice."} )
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

def results(request, question_id):
    question = get_object_or_404(Questions, pk = question_id)
    return render(request,'polls/result.html',{'question':question})

Polls url_patterns

urlpatterns = [
    path('',views.index,name='index'),
    path('<int:question_id>/',views.details, name='details'),
    path('<int:question_id>/results/',views.results, name='results'),
    path('<int:question_id>/vote/',views.vote, name='vote')
]

And polls/result.html

<h1>{{question.question_text}}</h1>
    
<ul>
        
    {% for choice in question.choice_set.all %}
        <li>{{choice.choice_text}} -- {{choice.votes}} votes {{choice.votes|pluralize}}</li>
    {% endfor %}
            
</ul>
<a href="{% url 'polls:vote' %}">Vote Again?</a>

Upvotes: 0

Views: 87

Answers (1)

Sohaib
Sohaib

Reputation: 594

You are missing the question_id in vote reverse url pattern. The below url must need an integer id

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

which you are not providing in reverse URL in html template.

<a href="{% url 'polls:vote' %}">Vote Again?</a> 

Pass the vote_id like

<a href="{% url 'polls:vote' vote_id %}">Vote Again?</a> 

Upvotes: 1

Related Questions