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
如何更改日期格式?也许是形式。py?
date
对象上调用str(…)
,从而得到结果。
然而,您可以做的是创建date
的子类,在其中更改日期格式:
from datetime import date, datetime
class customdate(date):
def__str__(self):
return datetime.strftime(self, '%d.%m.%Y')
那么我们可以将其用于我们的MinValueValidator
:
my_date = models.DateField(
'my date',
validators=[MinValueValidator(customdate(2021, 1, 14))],
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:['Ensure this value is greater than or equal to 14.01.2021.']