fix empty string as a value for a validated DecimalField (#8064) (#8067)

This commit is contained in:
Evgeny Panfilov 2021-07-01 17:04:44 +03:00 committed by GitHub
parent d2977cff98
commit 98e56e0327
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 3 deletions

View File

@ -1046,6 +1046,11 @@ class DecimalField(Field):
'Invalid rounding option %s. Valid values for rounding are: %s' % (rounding, valid_roundings))
self.rounding = rounding
def validate_empty_values(self, data):
if smart_str(data).strip() == '' and self.allow_null:
return (True, None)
return super().validate_empty_values(data)
def to_internal_value(self, data):
"""
Validate that the input is a decimal number and return a Decimal
@ -1063,9 +1068,6 @@ class DecimalField(Field):
try:
value = decimal.Decimal(data)
except decimal.DecimalException:
if data == '' and self.allow_null:
return None
self.fail('invalid')
if value.is_nan():

View File

@ -1163,6 +1163,30 @@ class TestMinMaxDecimalField(FieldValues):
)
class TestAllowEmptyStrDecimalFieldWithValidators(FieldValues):
"""
Check that empty string ('', ' ') is acceptable value for the DecimalField
if allow_null=True and there are max/min validators
"""
valid_inputs = {
None: None,
'': None,
' ': None,
' ': None,
5: Decimal('5'),
'0': Decimal('0'),
'10': Decimal('10'),
}
invalid_inputs = {
-1: ['Ensure this value is greater than or equal to 0.'],
11: ['Ensure this value is less than or equal to 10.'],
}
outputs = {
None: '',
}
field = serializers.DecimalField(max_digits=3, decimal_places=1, allow_null=True, min_value=0, max_value=10)
class TestNoMaxDigitsDecimalField(FieldValues):
field = serializers.DecimalField(
max_value=100, min_value=0,