4
Firstly, you can’t have required=False
on a BooleanField
, use NullBooleanField
instead:
- https://docs.djangoproject.com/en/dev/ref/models/fields/#booleanfield
- https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.NullBooleanField
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"})
2
I’m posting this answer because I had the same problem and Francis’s answer didn’t help me.
I eventually found the solution was to re-run manage.py syncdb
. My fields had previously been IntegerField and I had converted them to BooleanField. BooleanField read the presence of value=”0″ in the database as being initialized and checked. This is regardless of what your model says. You want to see:
<input checked="checked" id="id_cost_track_destruction" name="cost_track_destruction" type="checkbox">
when you inspect an element. Since this bug shows up in the Django Admin panel, it has nothing to do with your forms.py.
This is purely a model and database issue. Try regenerating your database if you’ve changed your models.py field types.
- [Django]-TruncDate timezone parameter is not working in Django
- [Django]-When a Web framework isn't convenient to use?
1
For those who are using ModelForms, this is what worked for me:
password_required = forms.CheckboxInput(attrs={'checked' : ''})
This correctly generates the checkbox with it unchecked.
- [Django]-Getting data from an Excel sheet
- [Django]-How to add if statement in filter?
- [Django]-Why do chat applications have to be asynchronous?