NoReverseMatch Exception help in Django

mportiz08 picture mportiz08 · Jul 30, 2009 · Viewed 19.3k times · Source

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

Answer

bstpierre picture bstpierre · Jul 30, 2009

Try using:

return HttpResponseRedirect(reverse('poll_results', kwargs={'object_id': p.id}))