Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django form with just a BooleanField

Tags:

People also ask

What is BooleanField Django?

BooleanField is a true/false field. It is like a bool field in C/C+++. The default form widget for this field is CheckboxInput, or NullBooleanSelect if null=True.

What is the difference between form and ModelForm in Django?

The main difference between the two is that in forms that are created from forms. ModelForm , we have to declare which model will be used to create our form. In our Article Form above we have this line " model = models. Article " which basically means we are going to use Article model to create our form.


I'm rather new to Django and I'm using Django 1.0. I have this:
forms.py:

class MyForm(forms.Form):
    extra_cheeze = forms.BooleanField(required=False,
                                      initial=False,
                                      label='Extra cheeze')

views.py:

def order_something(request):
    form = MyForm(request.POST or None)
    if request.method == 'POST' and form.is_valid():
        # do stuff...

The problem is that the form is not valid unless the checkbox is checked, so there doesn't seem to be a way to get a False value from the field. As far as I can understand from the docs, it should work. It works if I add a CharField to my form...

Am I misunderstanding something here or is this a bug? (Yes, I have googled but found nothing relevant)

Update: As suggested by @Dominic Rodger, I tried adding a hidden field
dummy = forms.CharField(initial='dummy', widget=forms.widgets.HiddenInput())
and that makes the form valid. This workaround enables me to move on right now, but it would still be interesting to know if I'm misunderstanding something...