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
-
from django.http import HttpResponse, Http404
2
from django.shortcuts import render, get_object_or_404
0
0
3
4
-
from .models import Question
5
6
# Create your views here.
7
···
26
return HttpResponse(response % question_id)
27
28
def vote(request, question_id):
29
-
return HttpResponse("You're voting on question %s." % question_id)
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
···
1
+
from django.http import HttpResponse, HttpResponseRedirect
2
from django.shortcuts import render, get_object_or_404
3
+
from django.db.models import F
4
+
from django.urls import reverse
5
6
+
from .models import Question, Choice
7
8
# Create your views here.
9
···
28
return HttpResponse(response % question_id)
29
30
def vote(request, 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,)))