Skip to content

Commit 99e8b40

Browse files
authored
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 <>
1 parent e08e606 commit 99e8b40

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

rest_framework/fields.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import decimal
55
import functools
66
import inspect
7+
import logging
78
import re
89
import uuid
910
from collections.abc import Mapping
@@ -38,6 +39,8 @@
3839
from rest_framework.utils.timezone import valid_datetime
3940
from rest_framework.validators import ProhibitSurrogateCharactersValidator
4041

42+
logger = logging.getLogger("rest_framework.fields")
43+
4144

4245
class empty:
4346
"""
@@ -990,6 +993,11 @@ def __init__(self, max_digits, decimal_places, coerce_to_string=None, max_value=
990993
self.max_value = max_value
991994
self.min_value = min_value
992995

996+
if self.max_value is not None and not isinstance(self.max_value, decimal.Decimal):
997+
logger.warning("max_value in DecimalField should be Decimal type.")
998+
if self.min_value is not None and not isinstance(self.min_value, decimal.Decimal):
999+
logger.warning("min_value in DecimalField should be Decimal type.")
1000+
9931001
if self.max_digits is not None and self.decimal_places is not None:
9941002
self.max_whole_digits = self.max_digits - self.decimal_places
9951003
else:

tests/test_fields.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1216,6 +1216,17 @@ class TestMinMaxDecimalField(FieldValues):
12161216
min_value=10, max_value=20
12171217
)
12181218

1219+
def test_warning_when_not_decimal_types(self, caplog):
1220+
import logging
1221+
serializers.DecimalField(
1222+
max_digits=3, decimal_places=1,
1223+
min_value=10, max_value=20
1224+
)
1225+
assert caplog.record_tuples == [
1226+
("rest_framework.fields", logging.WARNING, "max_value in DecimalField should be Decimal type."),
1227+
("rest_framework.fields", logging.WARNING, "min_value in DecimalField should be Decimal type.")
1228+
]
1229+
12191230

12201231
class TestAllowEmptyStrDecimalFieldWithValidators(FieldValues):
12211232
"""

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy