5

我有一个表格:

class myForm(forms.Form):        
     myBoolField = forms.BooleanField(
        label='myLabel', 
        required=True,
    )

下面是对应的模板:

<form action="." method="post" enctype="application/x-www-form-urlencoded"> 
    {% csrf_token %}
    {{ form.as_p }}

    <div class="form-actions">
        <button type="submit" class="btn btn-primary">Submit</button>
        <a class="btn" href="{{ secondary_action_url }}">{{ secondary_action_text }}</a>
    </div>
</form>

当 Django 呈现此模板时,myField 显示为一个空复选框。如果我选中该框,点击提交按钮会为 myField 的清理值生成“True”。但是,如果我将框留空并点击提交按钮,而不是得到“假”,我得到无。这根本不是我想要的。我希望此复选框返回 True 或 False。

我该怎么做才能让它像我想要(和期望)一样工作?我期望必填布尔字段返回 True 或 False 是否放错了位置?

4

1 回答 1

9
class myForm(forms.Form):        
     myBoolField = forms.BooleanField(
        label='myLabel', 
        required=False,
        initial=False
     )

如果您不想更深入地研究这个主题,这可以防止任何进一步的错误

edit after edit after edit: by marking required=True, you explicitly request an input from the user. by default, an unchecked checkbox doesn't get submitted (that's where the None value comes from) and your validation would fail everytime, because of the required.

于 2013-03-11T17:02:03.703 回答