diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 9b922ed918..4729854fd2 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -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): """ @@ -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, diff --git a/tests/test_fields.py b/tests/test_fields.py index 4cbbc030e3..57f205f1a9 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -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`.