Django学习(五)--给项目加入表单

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提交表单。但是这样显然不是应该发生的情况。

此处对于这种情况,我的解决方案

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值