草庐IT

python - Django 年验证在 2017 年返回 "Ensure this value is less than or equal to 2016"

coder 2023-08-26 原文

在我的数据库中,我有一个年份字段为 2016 的记录,但我需要将其更改为 2017。当我使用 Django admin 将其更改为 2017 时,我得到“确保此值小于或等于 2016。 ”。我的模型有什么问题?

class Track (models.Model):    
    artist = models.ForeignKey(Artist, blank=True, null=True, on_delete=models.SET_NULL, verbose_name="Artist")
    title = models.CharField(max_length=100, verbose_name="Title")
    year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[MinValueValidator(1900), MaxValueValidator(datetime.datetime.now().year)], verbose_name="Year")
    timestamp = models.DateTimeField(default=timezone.now)

最佳答案

这是 django 模型/表单等的经典问题!验证器中的 datetime.datetime.now().year 代码仅在第一次读取源文件时执行一次。并不是每次提交表单都执行!所以它在第一次执行时的值为 2016,现在仍然具有相同的值。

为了快速理解我的观点,请重新启动您的应用程序服务器 - 然后它应该没问题(模型将被重新评估并将 2017 年作为 datetime.date.today().year!)。当然,要真正解决这个问题,您必须更改验证逻辑以使用自定义验证器(不能使用 MaxValueValidator),该验证器将在每次提交表单时运行。

例如:

def my_year_validator(value):
    if value < 1900 or value > datetime.datetime.now().year:
        raise ValidationError(
            _('%(value)s is not a correcrt year!'),
            params={'value': value},
        )

...
# And then in your model:
year = models.PositiveSmallIntegerField(
    null=True, 
    blank=True, 
    validators=[my_year_validator], 
    verbose_name="Year"
)

关于python - Django 年验证在 2017 年返回 "Ensure this value is less than or equal to 2016",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41422565/

有关python - Django 年验证在 2017 年返回 "Ensure this value is less than or equal to 2016"的更多相关文章

随机推荐