Django表单
接上一篇我们在给项目添加几个视图模板,但是并没有对视图的细节做太多处理,这里继续对detail页面做一些补充
1.编写一个简单的表单
将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">
我们将name为choice的值(为某choice的id,这根我们的数据库列名对应)提交给Vote
所以接下来我们更改Vote
#请同步导入所需要的包!
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,)))
此处的 HttpResponseRedirect 只接收一个参数:用户将要被重定向的 URL,在 HttpResponseRedirect 的构造函数中使用 reverse() 函数。这个函数避免了我们在视图函数中硬编码 URL。它需要我们给出我们想要跳转的视图的名字和该视图所对应的 URL 模式中需要给该视图提供的参数。最终reverse() 调用将返回一个这样的字符串:'/polls/3/results/'
,就是说其中 3 是 question.id 的值。重定向的 URL 将调用 ‘results’ 视图来显示最终的页面。
到这一步我出现了一点问题
我在details方法中提交给vote方法处理的choice值不知道为什么传不过去,可以解决的办法是将CSRF设定去掉,然后将表单修改为普通的post提交表单。但是这样显然不是应该发生的情况。