如何使Min / MaxValueValidator与Django的DecimalField一起使用?

时间:2018-10-12 07:08:22

标签: python django validation decimal

在Django 2.1.2(Python 3.7.0)中似乎发生了奇怪的故障:

from django.db.models import DecimalField
from django.core.validators import MaxValueValidator, MinValueValidator
f = DecimalField(max_digits=4, decimal_places=2, validators=[MinValueValidator(10), MaxValueValidator(20)])

这是预期的行为:

>>> f.clean(15, model_instance=None)
Decimal('15')
>>> f.clean('15', model_instance=None)
Decimal('15')

但这不起作用:

>>> f.clean(5, model_instance=None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/.../anaconda3/envs/django/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 632, in clean
    self.run_validators(value)
  File "/Users/.../anaconda3/envs/django/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 591, in run_validators
    raise exceptions.ValidationError(errors)
django.core.exceptions.ValidationError: <exception str() failed>

相同错误:

>>> f.clean('5', model_instance=None)
>>> f.clean(25, model_instance=None)

我在做什么错了?

NB:我知道如何在ModelForm中手动验证此字段,但我希望避免变通方法。我已经检查了一些相关的答案,但均未成功:

0 个答案:

没有答案