1
+ # -*- coding: utf-8
2
+ from django .core .urlresolvers import reverse
3
+ from django .http import HttpResponseRedirect
1
4
from django .shortcuts import render , get_object_or_404
2
- from polls .models import Question
5
+ from polls .models import Question , Choice
3
6
4
7
5
8
def index (request ):
@@ -10,4 +13,22 @@ def index(request):
10
13
11
14
def detail (request , question_id ):
12
15
question = get_object_or_404 (Question , pk = question_id )
13
- return render (request , 'polls/detail.html' , {'question' : question })
16
+ return render (request , 'polls/detail.html' , {'question' : question })
17
+
18
+
19
+ def vote (request , question_id ):
20
+ p = get_object_or_404 (Question , pk = question_id )
21
+ try :
22
+ selected_choice = p .choice_set .get (pk = request .POST ['choice' ])
23
+ except (KeyError , Choice .DoesNotExist ):
24
+ # 설문 투표 폼을 다시 보여준다.
25
+ return render (request , 'polls/detail.html' , {
26
+ 'question' : p ,
27
+ 'error_message' : "You didn't select a choice." ,
28
+ })
29
+ else :
30
+ selected_choice .votes += 1
31
+ selected_choice .save ()
32
+ # POST 데이터를 정상적으로 처리하였으면,
33
+ # 항상 HttpResponseRedirect를 반환하여 리다이렉션 처리함
34
+ return HttpResponseRedirect (reverse ('polls:results' , args = (p .id ,)))
0 commit comments