1. 写一个简单的表单form
a. 改写polls/template/polls/detail.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="Vote" />
</form>
先看效果:
<form action="{% url 'polls:vote' question.id %}" method="post">
这一句告诉浏览器, 使用post方法将form data返回给URL'polls:vote' question.id
<input type="radio" name="choice" id="choice{
{ forloop.counter }}" value="{
{ choice.id }}" />
这行代码为question的每个choice都配置了一个radio按钮, 该按钮的名字是'choice', 该按钮的值关联了choice.id. 当选择了其中一个按钮并按提交按钮时, 将会发送系统一个POST data: choice=id
{
{ forloop.counter }}
是指for循环中当前循环次数
{% csrf_token %}
csrf是Cross Site Request Forgeries, 所有POST Form指向内部的URLs时需使用csrf_token语句.
b. 改写vote view处理表单提交的数据
提交了form之后, 需要创建与POST的URL对应的views.