diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 88d606b28..4bea5c419 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -919,7 +919,8 @@ class FloatField(Field): 'invalid': _('A valid number is required.'), 'max_value': _('Ensure this value is less than or equal to {max_value}.'), 'min_value': _('Ensure this value is greater than or equal to {min_value}.'), - 'max_string_length': _('String value too large.') + 'max_string_length': _('String value too large.'), + 'overflow': _('Integer value too large to convert to float') } MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs. @@ -945,6 +946,8 @@ class FloatField(Field): return float(data) except (TypeError, ValueError): self.fail('invalid') + except OverflowError: + self.fail('overflow') def to_representation(self, value): return float(value) diff --git a/tests/test_fields.py b/tests/test_fields.py index 3112fc2cc..bcdcf15d8 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -1,4 +1,5 @@ import datetime +import math import os import re import uuid @@ -1072,6 +1073,14 @@ class TestMinMaxFloatField(FieldValues): field = serializers.FloatField(min_value=1, max_value=3) +class TestFloatFieldOverFlowError(TestCase): + def test_overflow_error_float_field(self): + field = serializers.FloatField() + with pytest.raises(serializers.ValidationError) as exec_info: + field.to_internal_value(data=math.factorial(171)) + assert "Integer value too large to convert to float" in str(exec_info.value.detail) + + class TestDecimalField(FieldValues): """ Valid and invalid values for `DecimalField`.