views:

1931

answers:

2

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

+2  A: 

Try using:

return HttpResponseRedirect(reverse('poll_results', kwargs={'object_id': p.id}))
bstpierre
Thanks--that worked. Could you maybe explain how it differs from the version in the tutorial and why it wasn't working before?
mportiz08
Don't know about the tutorial. But it seems the generic view is using keyword arguments. The reverse resolver matches args and kwargs separately, so when you were passing args, it didn't match the view that used kwargs. But when you pass kwargs it works. Make sense?
bstpierre
Yeah, thanks alot!
mportiz08
A: 

Are you sure that's where your error really is? Based on the error message, it sounds like either in a view or in a template you are trying to reverse 'polls/poll_results' (in a template, you may be doing something like {% url polls/poll_results poll.pk %})

SmileyChris