Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 2 commits into from May 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 8 additions & 0 deletions rest_framework/fields.py
Expand Up @@ -4,6 +4,7 @@
import decimal
import functools
import inspect
import logging
import re
import uuid
from collections.abc import Mapping
Expand Down Expand Up @@ -38,6 +39,8 @@
from rest_framework.utils.timezone import valid_datetime
from rest_framework.validators import ProhibitSurrogateCharactersValidator

logger = logging.getLogger("rest_framework.fields")


class empty:
"""
Expand Down Expand Up @@ -990,6 +993,11 @@ def __init__(self, max_digits, decimal_places, coerce_to_string=None, max_value=
self.max_value = max_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:
self.max_whole_digits = self.max_digits - self.decimal_places
else:
Expand Down
11 changes: 11 additions & 0 deletions tests/test_fields.py
Expand Up @@ -1216,6 +1216,17 @@ class TestMinMaxDecimalField(FieldValues):
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):
"""
Expand Down