【问题标题】:Django form with checkbox is always False带有复选框的 Django 表单始终为 False
【发布时间】:2017-12-12 13:50:08
【问题描述】:

我正在寻找一个带有复选框的 Django 表单。无论我选中或取消选中该框的天气如何,在 POST 请求中都没有检测到它。这是模板的代码-

<form action="annotate_page" method="post">{% csrf_token %}

      <input id="repeat" type="checkbox" >
                <label for="repeat">Repeat Sentence?</label>


      <br>

      <button type="submit">Next</button><br>

 </form>

这是我的forms.py-

from django import forms

class AnnotateForm(forms.Form):
    repeat=forms.BooleanField(required=False)

这是我的观点逻辑-

if request.method=="POST":

    form = AnnotateForm(request.POST)

    if form.is_valid():
        print(request.POST)#prints only csrf_token in Query_dict
        print(form.cleaned_data["repeat"])#Always false

不管复选框是否被选中,打印语句总是给出 False。

我知道有类似的问题,但它们并没有解决我的问题。

【问题讨论】:

  • 在表单定义中,复选框被命名为repeat。但是在您的 html 模板中,复选框根本没有名称! (id 是repeat,但这不是一回事。)
  • 为什么还要在 html 中硬编码表单字段?使用{{ form.as_p }},Django 将为您绘制表单。

标签: python django checkbox


【解决方案1】:
<form action="annotate_page" method="post">{% csrf_token %}

      <input id="repeat" name="something" type="checkbox" >
                <label for="repeat">Repeat Sentence?</label>


      <br>

      <button type="submit">Next</button><br>

 </form>

在视野中

if request.method=="POST":

    form = AnnotateForm(request.POST)

    if form.is_valid():
        print(request.POST)#prints only csrf_token in Query_dict
        print(form.cleaned_data["something"])#Always false

您需要在输入字段中输入名称,否则将不会被捕获

【讨论】:

    猜你喜欢
    • 2015-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    相关资源
    最近更新 更多