Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork7k
Permit mixed casing of string values for BooleanField validation#8970
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Permit mixed casing of string values for BooleanField validation#8970
Uh oh!
There was an error while loading.Please reload this page.
Conversation
auvipy left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others.Learn more.
I need more detail here. how django handle boolean values?
saadullahaleem commentedMay 4, 2023
This is a good fix. I initially thought that Django itself simply works with classBooleanField(Field):widget=CheckboxInputdefto_python(self,value):"""Return a Python boolean object."""# Explicitly check for the string 'False', which is what a hidden field# will submit for False. Also check for '0', since this is what# RadioSelect will provide. Because bool("True") == bool('1') == True,# we don't need to handle that explicitly.ifisinstance(value,str)andvalue.lower()in ("false","0"):value=Falseelse:value=bool(value)returnsuper().to_python(value)defvalidate(self,value):ifnotvalueandself.required:raiseValidationError(self.error_messages["required"],code="required")defhas_changed(self,initial,data):ifself.disabled:returnFalse# Sometimes data or initial may be a string equivalent of a boolean# so we should run it through to_python first to get a boolean valuereturnself.to_python(initial)!=self.to_python(data) Django performs explicit checks too. The comments suggest that they're there to handle output of the form fields. |
Description
In this PR, all values of type
strbeing serialized toboolfor fields typedBooleanFieldare first cast to lowercase andthen validated against the lists ofTRUE_VALUES,FALSE_VALUES, andNULL_VALUES. Discovered this restriction when a user tried to send "Yes" as a valid value for a Boolean field to my team's Public-facing API.