Skip to content

Commit e289e6d

Browse files
committed
django tutorial: part 4, handling POST and more views.
1 parent fda3c34 commit e289e6d

File tree

2 files changed

+30
-8
lines changed

2 files changed

+30
-8
lines changed
+9-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
<h1>{{ question.question_text }}</h1>
2-
<ul>
2+
3+
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
4+
5+
<form action="{% url 'polls:vote' question.id %}" method="post">
6+
{% csrf_token %}
37
{% for choice in question.choice_set.all %}
4-
<li>{{ choice.choice_text }}</li>
8+
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
9+
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
510
{% endfor %}
6-
</ul>
11+
<input type="submit" value="Vote" />
12+
</form>

mysite/polls/views.py

+21-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
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
33
from django.shortcuts import render, get_object_or_404
4+
from django.core.urlresolvers import reverse
45

56

67
# Create your views here.
@@ -16,9 +17,24 @@ def detail(request, question_id):
1617

1718

1819
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})
2122

2223

2324
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

Comments
 (0)