feat: enforce Decimal type in min_value and max_value arguments of DecimalField (#8972)

* add warning when min_value and max_value are not decimal

* remove redundant module name in log

---------

Co-authored-by: ismaeljs <>
This commit is contained in:
Ismael Jiménez Sánchez 2023-05-09 16:50:29 +02:00 committed by GitHub
parent e08e606c82
commit 99e8b4033e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 0 deletions

View File

@ -4,6 +4,7 @@ import datetime
import decimal import decimal
import functools import functools
import inspect import inspect
import logging
import re import re
import uuid import uuid
from collections.abc import Mapping from collections.abc import Mapping
@ -38,6 +39,8 @@ from rest_framework.utils.formatting import lazy_format
from rest_framework.utils.timezone import valid_datetime from rest_framework.utils.timezone import valid_datetime
from rest_framework.validators import ProhibitSurrogateCharactersValidator from rest_framework.validators import ProhibitSurrogateCharactersValidator
logger = logging.getLogger("rest_framework.fields")
class empty: class empty:
""" """
@ -990,6 +993,11 @@ class DecimalField(Field):
self.max_value = max_value self.max_value = max_value
self.min_value = min_value self.min_value = min_value
if self.max_value is not None and not isinstance(self.max_value, decimal.Decimal):
logger.warning("max_value in DecimalField should be Decimal type.")
if self.min_value is not None and not isinstance(self.min_value, decimal.Decimal):
logger.warning("min_value in DecimalField should be Decimal type.")
if self.max_digits is not None and self.decimal_places is not None: if self.max_digits is not None and self.decimal_places is not None:
self.max_whole_digits = self.max_digits - self.decimal_places self.max_whole_digits = self.max_digits - self.decimal_places
else: else:

View File

@ -1216,6 +1216,17 @@ class TestMinMaxDecimalField(FieldValues):
min_value=10, max_value=20 min_value=10, max_value=20
) )
def test_warning_when_not_decimal_types(self, caplog):
import logging
serializers.DecimalField(
max_digits=3, decimal_places=1,
min_value=10, max_value=20
)
assert caplog.record_tuples == [
("rest_framework.fields", logging.WARNING, "max_value in DecimalField should be Decimal type."),
("rest_framework.fields", logging.WARNING, "min_value in DecimalField should be Decimal type.")
]
class TestAllowEmptyStrDecimalFieldWithValidators(FieldValues): class TestAllowEmptyStrDecimalFieldWithValidators(FieldValues):
""" """