Reputation: 229
def vote(request, poll_id, choice_id):
try:
poll = Poll.objects.get(pk = poll_id)
choice = Choice.objects.get(poll=poll, pk=choice_id)
choice.votes +=1
url = '/polls/' + poll_id
return HttpResponseRedirect(url)
except Poll.DoesNotExist or Choice.DoesNotExist:
return Http404
I am running with the Django tutorial and trying to make it functional before looking at the rest of the chapters and am stuck with a voting feature for the example poll feature.
I have the poll description function display a page with the current votes and choices for each poll, and am trying to get this vote view to just add one vote and return the user to the poll's description page you were looking at.
I tried doing the manual manipulation in the shell right and the function redirects you back to the poll description page, but the actual vote number never changes. What is wrong with my code? Thanks
Upvotes: 0
Views: 35
Reputation: 53386
You missed saving the object after incrementing the vote.
def vote(request, poll_id, choice_id):
try:
poll = Poll.objects.get(pk = poll_id)
choice = Choice.objects.get(poll=poll, pk=choice_id)
choice.votes +=1
## Saves in database otherwise updates are lost.
choice.save()
url = '/polls/' + poll_id
return HttpResponseRedirect(url)
except Poll.DoesNotExist or Choice.DoesNotExist:
return Http404
Upvotes: 3