3👍
From django’s documentation
Since all Field subclasses have required=True by default, the
validation condition here is important. If you want to include a
boolean in your form that can be either True or False (e.g. a checked
or unchecked checkbox), you must remember to pass in required=False
when creating the BooleanField.
2👍
I agree that this is incorrect behavior.
This should do for a specific field:
class BogusForm(forms.Form):
bogus_bool = forms.BooleanField(required=False)
def clean_bogus_bool(self):
field_name = 'bogus_bool'
if field_name not in self.data:
raise forms.ValidationError("This field is required.")
return self.cleaned_data[field_name]
This should do it for all bool fields on the form:
class BooleanFieldsRequiredMixin(forms.Form):
def clean(self):
for field_name, field in self.fields.iteritems():
# Only BooleanField not subclasses of it.
if type(field) is not forms.BooleanField:
continue
if field_name not in self.data:
self._errors[field_name] = self.error_class(["This field is required."])
return super(BooleanFieldsRequiredMixin, self).clean()
class BogusForm(BooleanFieldsRequiredMixin, forms.Form):
bogus_bool = forms.BooleanField(required=False)
There is a way to make this nicer by not requiring that required=False
bit on the boolean field, but it’s not worth the effort at the moment.
0👍
It’s because your bogus_bool is a required field by default.
class BogusForm(forms.Form):
bogus_bool = forms.BooleanField(required=False)
should do the trick.
👤Greg
- [Django]-How to do a syncdb with django, when migrations are also involved
- [Django]-Django get first part of a string
Source:stackexchange.com