Django HTML表单,讲解HTML表单在Django中的应用之前,先进行必要的准备工作。
将Choice模型注册到admin网站,修改polls/admin.py
:
# www.coolcou.com
from django.contrib import admin
from .models import Question, Choice
admin.site.register(Question)
admin.site.register(Choice)
登录admin后台,为问卷添加选项:单击“增加”按钮,进入添加问卷选项页面,如图所示。
添加三个选项,如图所示:
完成准备工作后,继续修改polls/detail.html
模板,为其添加HTML表单用于提交信息,新模板如下:
<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="提交 " />
</form>
以上模板简单介绍如下:
- 在问卷页显示问卷相关选项,并为每一个选项添加单选按钮(radio)。
- 表单的处理页用url模板标签表示
"{% url 'polls:vote' question.id %}"
,表单以post的方式提交。 forloop.counter
标签用于记录循环次数。- 由于当前表单使用post方式提交数据,我们需要防止伪造的跨域请求,表单中的
{% csrf_token %}
标签就可以解决这类问题。
接下来创建一个视图来接收并处理表单提交信息:
# www.coolcou.com
from django.shortcuts import get_object_or_404,render
from django.http import HttpResponseRedirect, HttpResponse
from django.utils import reverse
from .models import Question, choice
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):
# 没有选择任何答案,返回问卷业
return render(request, 'polls/detail.html',{
'question' : question,
'error_message':"还没有选择任何选项",
})
else:
selected_choice.votes += 1
selected_choice.save()
# 为了防止用户在提交数据结束后,单击浏览器后退按钮重新提交数据
# 必须使用 HttpResponseRedirect 方法进行页面跳转
return HttpResponseRedirect(reverse('polls:results', args=(question.id, )))
对以上视图做简单介绍如下:
(1)request.POST['choice']:POST
提交数据是一个字典,因此该语句表示在提交信息检索choice值。如果表单提交信息中不存在choice则抛出KeyError。
(2)信息处理结束后,使用HttpResponseRedirect方法跳转到新的页面以免用户单击浏览器后退按钮重新提交表单。
(3)为了防止在HttpResponseRedirect方法中使用URL硬编码,使用reverse()方法强制调用URL名,而不是直接使用URL。
修改results视图:
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question': question})
新建polls/results.html
模板并添加以下代码:
<h1>{{ question.question_text }}</h1>>
<ul>
{% for choice in question.choice_set.all %}
<li>
{{ choice.choice_text }} -- 计票 {{ choice.votes }}{{ choice.votes|pluralize}}次
</li>
{% endfor %}
</ul>
<a href="{% url 'polls:detail' question.id %}">重新投票?</a>
到目前为止,一个简单的投票系统就做好了,登录网站测试一下。
打开投票系统http://127.0.0.1:8000/polls/,如图所示:
单击问卷链接,打开如图所示的界面。
选择任意选项,单击“提交”按钮,打开如图所示的界面。
酷客教程相关文章:
评论前必须登录!
注册