NoReverseMatch Exception help in Django


Question

I'm fairly new to python and following along with part 4 of the tutorial for the Django framework here. I'm trying to implement generic views for the polls app--my code seems correct (as far as I can tell), but when I try to vote, I get a NoReverseMatch Exception that states:

Reverse for 'polls/poll_results' with arguments '(1L,)' and keyword arguments '{}' not found.

My code was working perfectly before I attempted the generic views, but I can't seem pinpoint the problem now.

Here's the code for my urls.py in the poll directory:

from django.conf.urls.defaults import *
from djtest.polls.models import Poll

info_dict = {
    'queryset': Poll.objects.all(),
}

urlpatterns = patterns('',
    (r'^$', 'django.views.generic.list_detail.object_list', info_dict),
    (r'^(?P<object_id>\d+)/$', 'django.views.generic.list_detail.object_detail', info_dict),
    url(r'^(?P<object_id>\d+)/results/$', 'django.views.generic.list_detail.object_detail', dict(info_dict, template_name='polls/results.html'), 'poll_results'),
    (r'^(?P<poll_id>\d+)/vote/$', 'djtest.polls.views.vote'),
)

And here is the views.py:

from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.core.urlresolvers import reverse
from djtest.polls.models import Poll, Choice

def vote(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        #redisplay form
        return render_to_response('polls/poll_detail.html', {
            'object': p,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()       
        return HttpResponseRedirect(reverse('poll_results', args=(p.id,)))

I have a feeling that it is a syntactical error, but I can't find it. Thanks in advance for any help...

1
10
7/30/2009 2:24:17 AM

Accepted Answer

Try using:

return HttpResponseRedirect(reverse('poll_results', kwargs={'object_id': p.id}))
5
7/30/2009 3:27:37 AM

I could not find any explanation that fixed the problem, until I ran across this person's abridged Django tutorial: http://tony.abou-assaleh.net/web-development/stripped-down-django-tutorial

It's basically a line in the details template, which should be:

<form action="/polls/{{ poll.id }}/vote/" method="post">

Instead of:

<form action="{% url 'polls.views.vote' poll.id %}" method="post">

I'm not sure why this fixed the issue, but it did for me. I'd love an explanation if anyone has one.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon