diff --git a/django/forms/fields.py b/django/forms/fields.py index 12316a1ab1..581d32d923 100644 --- a/django/forms/fields.py +++ b/django/forms/fields.py @@ -240,6 +240,12 @@ class DecimalField(Field): except DecimalException: raise ValidationError(self.error_messages['invalid']) + # Check for NaN, Inf and -Inf values. We can't compare directly for NaN, + # since it is never equal to itself. However, NaN is the only value that + # isn't equal to itself, so we can use this to identify NaN + if value != value or value == Decimal("Inf") or value == Decimal("-Inf"): + raise ValidationError(self.error_messages['invalid']) + sign, digittuple, exponent = value.as_tuple() decimals = abs(exponent) # digittuple doesn't include any leading zeros. diff --git a/tests/regressiontests/forms/fields.py b/tests/regressiontests/forms/fields.py index 9d407d9ea7..48da0f9e1d 100644 --- a/tests/regressiontests/forms/fields.py +++ b/tests/regressiontests/forms/fields.py @@ -320,6 +320,18 @@ True True >>> f.clean(Decimal('3.14')) == Decimal("3.14") True +>>> f.clean('NaN') +Traceback (most recent call last): +... +ValidationError: [u'Enter a number.'] +>>> f.clean('Inf') +Traceback (most recent call last): +... +ValidationError: [u'Enter a number.'] +>>> f.clean('-Inf') +Traceback (most recent call last): +... +ValidationError: [u'Enter a number.'] >>> f.clean('a') Traceback (most recent call last): ...