#33874 closed Bug (invalid)

BooleanField validate function should use ‘value is not None’ instead of 'not value'

Reported by: winng Owned by: nobody
Component: Forms Version: 3.2
Severity: Normal Keywords: form BooleanField validate
Cc: houtianhong502@… Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

https://github.com/django/django/blob/a5eba20f40a78a0d6236908502e450905afabbd7/django/forms/fields.py#L730

When booleanfield is False, it will meet the condition not value and self.required and raise ValidationError(self.error_messages['required'], code='required')

>>> from django import forms
>>> f = forms.BooleanField()
>>> f.clean("False") 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\projects\library_manager\venv\lib\site-packages\django\forms\fields.py", line 150, in clean
    self.validate(value)
  File "D:\projects\library_manager\venv\lib\site-packages\django\forms\fields.py", line 720, in validate
    raise ValidationError(self.error_messages['required'], code='required')
django.core.exceptions.ValidationError: <exception str() failed>
>>> f.clean("")      
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\projects\library_manager\venv\lib\site-packages\django\forms\fields.py", line 150, in clean
    self.validate(value)
  File "D:\projects\library_manager\venv\lib\site-packages\django\forms\fields.py", line 720, in validate
    raise ValidationError(self.error_messages['required'], code='required')
django.core.exceptions.ValidationError: <exception str() failed>
>>> f.clean("True") 
True

Change History (1)

comment:1 by Mariusz Felisiak, 22 months ago

Resolution: invalid
Status: newclosed
Summary: BooleanField in django/django/forms/fields.py validate function should use ‘value is not None’ instead of 'not value'BooleanField validate function should use ‘value is not None’ instead of 'not value'

This an intended and documented behavior:

"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."

Note: See TracTickets for help on using tickets.
Back to Top