如何更改 Django 中 MinValueValidator 错误消息中的日期格式?

How to change date format in MinValueValidator error message in Django?

我在模型中有一个字段:

my_date = models.DateField('my date', validators=[MinValueValidator(date(2021, 1, 14))], null=True)

当 my_date 早于 2021-1-14 时,我收到消息:

Ensure this value is greater than or equal to 2021-01-14

但我想要日期格式:“%d.%m.%Y” 所以应该是:

Ensure this value is greater than or equal to 01.14.2021

如何更改日期格式?也许在 forms.py?

Django 将在 date 对象上调用 str(…),因此会出现该结果。

然而,您可以做的是创建 date 的子类,您可以在其中更改日期格式:

from datetime import date, datetime

class customdate(<strong>date</strong>):
    def <strong>__str__</strong>(self):
        return datetime.strftime(self, '%d.%m.%Y')

然后我们可以将其用于 MinValueValidator:

my_date = models.DateField(
    'my date',
    validators=[MinValueValidator(<strong>customdate(</strong>2021, 1, 14<strong>)</strong>)],
    null=True
)

这会产生错误消息:

>>> from django.core.validators import MinValueValidator
>>> mvv = MinValueValidator(customdate(2021, 1, 14))
>>> mvv(date(1958, 3, 25))
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/djangotest/env/lib/python3.8/site-packages/django/core/validators.py", line 343, in __call__
    raise ValidationError(self.message, code=self.code, params=params)
django.core.exceptions.ValidationError: <strong>['Ensure this value is greater than or equal to 14.01.2021.']</strong>