Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion rest_framework/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -1067,7 +1067,12 @@ def to_internal_value(self, data):
if value in (decimal.Decimal('Inf'), decimal.Decimal('-Inf')):
self.fail('invalid')

return self.quantize(self.validate_precision(value))
try:
return self.quantize(self.validate_precision(value))
except decimal.InvalidOperation:
# Only possible without max_digits: the value needs more digits
# than quantize() allows.
self.fail('max_string_length')

def validate_precision(self, value):
"""
Expand Down Expand Up @@ -1138,6 +1143,12 @@ def quantize(self, value):
context = decimal.getcontext().copy()
if self.max_digits is not None:
context.prec = self.max_digits
else:
# No digit limit: make room for the quantized value, which may need
# more digits than the default context precision (28), within the
# same bound as the input string.
digits = max(value.adjusted(), 0) + 1 + self.decimal_places
context.prec = max(context.prec, min(digits, self.MAX_STRING_LENGTH))
return value.quantize(
decimal.Decimal('.1') ** self.decimal_places,
rounding=self.rounding,
Expand Down
19 changes: 19 additions & 0 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -1431,6 +1431,25 @@ class TestNoMaxDigitsDecimalField(FieldValues):
outputs = {}


class TestNoMaxDigitsLargeDecimalField(FieldValues):
"""
Without max_digits, values longer than the default decimal context
precision (28 digits) are quantized, not rejected with a server error.
"""
field = serializers.DecimalField(decimal_places=2, max_digits=None)
valid_inputs = {
'1' * 27: Decimal('1' * 27 + '.00'),
'1e30': Decimal('1' + '0' * 30 + '.00'),
10 ** 30: Decimal('1' + '0' * 30 + '.00'),
}
invalid_inputs = {
'1e1000': ['String value too large.'],
}
outputs = {
Decimal('1' * 30): '1' * 30 + '.00',
}


class TestNoStringCoercionDecimalField(FieldValues):
"""
Output values for `DecimalField` with `coerce_to_string=False`.
Expand Down