1
- from django .http import HttpResponse
2
- from polls .models import Question
1
+ from django .http import HttpResponse , HttpResponseRedirect
2
+ from polls .models import Choice , Question
3
3
from django .shortcuts import render , get_object_or_404
4
+ from django .core .urlresolvers import reverse
4
5
5
6
6
7
# Create your views here.
@@ -16,9 +17,24 @@ def detail(request, question_id):
16
17
17
18
18
19
def results (request , question_id ):
19
- response = "You're looking at the results of question %s."
20
- return HttpResponse ( response % question_id )
20
+ question = get_object_or_404 ( Question , pk = question_id )
21
+ return render ( request , 'polls/results.html' , { 'question' : question } )
21
22
22
23
23
24
def vote (request , question_id ):
24
- return HttpResponse ("You're voting on question %s." % question_id )
25
+ p = get_object_or_404 (Question , pk = question_id )
26
+ try :
27
+ selected_choice = p .choice_set .get (pk = request .POST ['choice' ])
28
+ except (KeyError , Choice .DoesNotExist ):
29
+ # Redisplay the question voting form.
30
+ return render (request , 'polls/detail.html' , {
31
+ 'question' : p ,
32
+ 'error_message' : "You didn't select a choice." ,
33
+ })
34
+ else :
35
+ selected_choice .votes += 1
36
+ selected_choice .save ()
37
+ # Always return an HttpResponseRedirect after successfully dealing
38
+ # with POST data. This prevents data from being posted twice if a
39
+ # user hits the Back button.
40
+ return HttpResponseRedirect (reverse ('polls:results' , args = (p .id ,)))
0 commit comments