投票URL
polls/urls.py:
1
2
|
# ex: /polls/5/vote/
url(r
'^(?P<question_id>[0-9]+)/vote/$'
, views.vote, name
=
'vote'
),
|
创建投票form表单
polls/templates/polls/detail.html:
1
2
3
4
5
6
7
8
9
10
11
12
|
<
h1
>{{ question.question_text }}</
h1
>
{% if error_message %}<
p
><
strong
>{{ error_message }}</
strong
></
p
>{% endif %}
<
form
action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
<
input
type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"/>
<
label
for="choice{{ forloop.counter }}">{{ choice.choice_text }}</
label
><
br
/>
{% endfor %}
<
input
type="submit" value="Vote"/>
</
form
>
|
代码解释:
{{ forloop.counter }} : for 循环次数
{% csrf_token %} : 解决POST请求跨域问题 Cross Site Request Forgeries
{% if %} {% endif %}:判断
{% for %} {% endfor %}:循环
投票Views 逻辑处理
投票 views vote in polls/views.py:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
from
django.http
import
HttpResponse, HttpResponseRedirect
from
django.urls
import
reverse
def
vote(request, question_id):
question
=
get_object_or_404(Question, pk
=
question_id)
try
:
selected_choice
=
question.choice_set.get(pk
=
request.POST[
'choice'
])
except
(KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return
render(request,
'polls/detail.html'
, {
'question'
: question,
'error_message'
:
"You didn't select a choice."
,
})
else
:
selected_choice.votes
+
=
1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return
HttpResponseRedirect(reverse(
'polls:results'
, args
=
(question.
id
,)))
|
代码解释:
request.POST,request.GET: 分别可获得POST或GET方法的参数值,如上 request.POST['choice'] 可取得POST请求中,name值为choice的Value值。若POST参数中没有choice,则会产生KeyError。
HttpResponseRedirect:重定向跳转,提交成功后进行自动重定向跳转是web 开发的一个良好实践。防止数据提交两次。
投票结果页 Views 逻辑处理
views results in polls/views.py:
1
2
3
4
5
|
from
django.shortcuts
import
get_object_or_404, render
def
results(request, question_id):
question
=
get_object_or_404(Question, pk
=
question_id)
return
render(request,
'polls/results.html'
, {
'question'
: question})
|
投票结果显示 template
polls/templates/polls/results.html:
1
2
3
4
5
6
7
8
9
|
<
h1
>{{ question.question_text }}</
h1
>
<
ul
>
{% for choice in question.choice_set.all %}
<
li
>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</
li
>
{% endfor %}
</
ul
>
<
a
href="{% url 'polls:detail' question.id %}">Vote again?</
a
>
|
实现结果
1、访问detail.html:http://localhost:8000/polls/1/
2、选择后,点击vote投票,跳转到结果页 results.html