Python – Django BooleanField always checked even when value is false

djangodjango-formspython

I have a BooleanField in a standard Django Form defined as:

my_boolean_field = BooleanField(initial=True)

when I render my form with initial data, and my_boolean_field is set to an initial value of False, when the form renders it is still checked despite the fact that the value is false as the html shows:

<p><label for="id_2">my_boolean_field</label>: 
    <input checked="checked" 
           type="checkbox" 
           name="2" 
           value="False" 
           id="id_2" /> 
</p>

Has anyone else experienced this, or knows how to fix it so that when the initial data/input value is false then the checkbox is not checked?

UPDATE: Even if I remove the initial=True argument from the BooleanField the same thing happens.

Best Answer

Firstly, you can't have required=False on a BooleanField, use NullBooleanField instead:

let me know what the HTML output of the new widget is once you've done this?

EDIT

I assumed that this is a ModelForm. Is this a regular django.forms.Form?

EDIT 2

My test form:

from django import forms

class MyForm(forms.Form) :
    """The test form"""
    my_boolean_field = forms.BooleanField(initial=True)

My template:

<div>
{{ form.my_boolean_field.label_tag }}
{{ form.my_boolean_field }}
{{ form.my_boolean_field.errors }}
</div>

This is what I get for output when I view page source. EDITED

<div>
<label for="id_my_boolean_field">My boolean field</label>
<input type="checkbox" name="my_boolean_field" id="id_my_boolean_field" />
</div>

My View NEW

form = MyForm(initial={'my_boolean_field':False})

What you are showing and what I'm seeing aren't matching up. paste your full form, view and template please?

EDIT 3

I only see output like this:

<div>
<label for="id_my_boolean_field">My boolean field</label>
<input checked="checked" type="checkbox" name="my_boolean_field" value="False" id="id_my_boolean_field" />
</div>

when I put False in quotes:

form = FormLogin(initial={'my_boolean_field':"False"})
Related Topic