Nishant Nawarkhede
Nishant Nawarkhede

Reputation: 8400

django form should return data based on string comparison

Here is django form,

In [61]: from django import forms

In [62]: class myform(forms.Form):
    ...:     f = forms.BooleanField()
    ...:

In [63]: x = myform({'f': '0'})

In [64]: x.is_valid()
Out[64]: True

In [65]: x.cleaned_data
Out[65]: {'f': True}

I am passing f as '0', cleaned_data is returning f as True.

Expected behaviour :

form should return False for '0' and True for '1', How do I achieve this ?

Upvotes: 0

Views: 50

Answers (1)

Daniel Hepper
Daniel Hepper

Reputation: 29967

By default, forms.BooleanField uses a CheckboxInput widget. Unchecked checkboxes do not send any data when submitting a form, so the CheckboxInput widget considers any non-empty input to be True.

You can work around this by using a RadioSelectInput widget:

>>> class myform(forms.Form):
...   f = forms.BooleanField(widget=forms.RadioSelect, required=False)
...
>>> x = myform({'f': '0'})
>>> x.is_valid()
True
>>> x.cleaned_data
{'f': False}
>>> x = myform({'f': '1'})
>>> x.is_valid()
True
>>> x.cleaned_data
{'f': True}

Note that you have to set required=False, otherwise the form won't validate for falsy values.

If you are only using the form to validate data and not to render the HTML, you might want to consider creating your own form field class.

Upvotes: 2

Related Questions