tangled
alpha
login
or
join now
baileykane.co
/
django-hello-world
0
fork
atom
this repo has no description
0
fork
atom
overview
issues
pulls
pipelines
Add logic for handling vote submissions
baileykane.co
6 months ago
e7510974
3773e1de
+20
-3
1 changed file
expand all
collapse all
unified
split
polls
views.py
+20
-3
polls/views.py
···
1
1
-
from django.http import HttpResponse, Http404
1
1
+
from django.http import HttpResponse, HttpResponseRedirect
2
2
from django.shortcuts import render, get_object_or_404
3
3
+
from django.db.models import F
4
4
+
from django.urls import reverse
3
5
4
4
-
from .models import Question
6
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
29
-
return HttpResponse("You're voting on question %s." % question_id)
31
31
+
question = get_object_or_404(Question, pk=question_id)
32
32
+
try:
33
33
+
selected_choice = question.choice_set.get(pk=request.POST["choice"])
34
34
+
except (KeyError, Choice.DoesNotExist):
35
35
+
# If no choice was selected, re-render the question voting form.
36
36
+
return render(request, "polls/detail.html", {
37
37
+
"question": question,
38
38
+
"error_message": "You didn't select a choice.",
39
39
+
},)
40
40
+
else:
41
41
+
selected_choice.votes = F("votes") + 1
42
42
+
selected_choice.save()
43
43
+
# Always return an HttpResponseRedirect after successfully dealing
44
44
+
# with POST data. This prevents data from being posted twice if a
45
45
+
# user hits the back button.
46
46
+
return HttpResponseRedirect(reverse("polls:results", args=(question.id,)))