this repo has no description

Add logic for handling vote submissions

+20 -3
+20 -3
polls/views.py
··· 1 - from django.http import HttpResponse, Http404 1 + from django.http import HttpResponse, HttpResponseRedirect 2 2 from django.shortcuts import render, get_object_or_404 3 + from django.db.models import F 4 + from django.urls import reverse 3 5 4 - from .models import Question 6 + from .models import Question, Choice 5 7 6 8 # Create your views here. 7 9 ··· 26 28 return HttpResponse(response % question_id) 27 29 28 30 def vote(request, question_id): 29 - return HttpResponse("You're voting on question %s." % question_id) 31 + question = get_object_or_404(Question, pk=question_id) 32 + try: 33 + selected_choice = question.choice_set.get(pk=request.POST["choice"]) 34 + except (KeyError, Choice.DoesNotExist): 35 + # If no choice was selected, re-render the question voting form. 36 + return render(request, "polls/detail.html", { 37 + "question": question, 38 + "error_message": "You didn't select a choice.", 39 + },) 40 + else: 41 + selected_choice.votes = F("votes") + 1 42 + selected_choice.save() 43 + # Always return an HttpResponseRedirect after successfully dealing 44 + # with POST data. This prevents data from being posted twice if a 45 + # user hits the back button. 46 + return HttpResponseRedirect(reverse("polls:results", args=(question.id,)))