Skip to content

Commit 98e56e0

Browse files
authored
fix empty string as a value for a validated DecimalField (#8064) (#8067)
1 parent d2977cf commit 98e56e0

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

rest_framework/fields.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1046,6 +1046,11 @@ def __init__(self, max_digits, decimal_places, coerce_to_string=None, max_value=
10461046
'Invalid rounding option %s. Valid values for rounding are: %s' % (rounding, valid_roundings))
10471047
self.rounding = rounding
10481048

1049+
def validate_empty_values(self, data):
1050+
if smart_str(data).strip() == '' and self.allow_null:
1051+
return (True, None)
1052+
return super().validate_empty_values(data)
1053+
10491054
def to_internal_value(self, data):
10501055
"""
10511056
Validate that the input is a decimal number and return a Decimal
@@ -1063,9 +1068,6 @@ def to_internal_value(self, data):
10631068
try:
10641069
value = decimal.Decimal(data)
10651070
except decimal.DecimalException:
1066-
if data == '' and self.allow_null:
1067-
return None
1068-
10691071
self.fail('invalid')
10701072

10711073
if value.is_nan():

tests/test_fields.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1163,6 +1163,30 @@ class TestMinMaxDecimalField(FieldValues):
11631163
)
11641164

11651165

1166+
class TestAllowEmptyStrDecimalFieldWithValidators(FieldValues):
1167+
"""
1168+
Check that empty string ('', ' ') is acceptable value for the DecimalField
1169+
if allow_null=True and there are max/min validators
1170+
"""
1171+
valid_inputs = {
1172+
None: None,
1173+
'': None,
1174+
' ': None,
1175+
' ': None,
1176+
5: Decimal('5'),
1177+
'0': Decimal('0'),
1178+
'10': Decimal('10'),
1179+
}
1180+
invalid_inputs = {
1181+
-1: ['Ensure this value is greater than or equal to 0.'],
1182+
11: ['Ensure this value is less than or equal to 10.'],
1183+
}
1184+
outputs = {
1185+
None: '',
1186+
}
1187+
field = serializers.DecimalField(max_digits=3, decimal_places=1, allow_null=True, min_value=0, max_value=10)
1188+
1189+
11661190
class TestNoMaxDigitsDecimalField(FieldValues):
11671191
field = serializers.DecimalField(
11681192
max_value=100, min_value=0,

0 commit comments

Comments
 (0)