Django Forms: Why doesn't boolean field work as I expect it?
django-forms
Solution
class myForm(forms.Form):
myBoolField = forms.BooleanField(
label='myLabel',
required=False,
initial=False
)
this prevents any further error, if you don't want to go deeper into this subject
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.
Problem
I have a form: ``` class myForm(forms.Form): myBoolField = forms.BooleanField( label='myLabel', required=True, ) ``` Here is the corresponding template: ``` <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> ``` When Django renders this template myField shows up as an empty checkbox. If I check the box, hitting the submit button yields "True" for the cleaned value of myField. However, If I leave the box empty and hit the submit button, instead of getting "False", I get None. That's not at all what I want. I want this check box to return True or False. What do I do to make it work like I want (and expect)? Is my expectation that a Required Boolean field returns True or False misplaced?