python - 验证datefield,以便它不会在Django中使用将来的日期?

标签 python django python-3.x django-models

我正在为我的项目创建一个网站,并且有一个名为Purchase_Date的字段:

class Member_Registration(models.Model):
    Purchase_Date=models.DateField(max_length=10, help_text="Enter the date of purchase")

如果用户选择将来的日期,我想抛出一个错误。我该怎么办?

最佳答案

您想要的是validator:

from datetime import date
from django.core.exceptions import ValidationError
from django.db import models

def no_future(value):
    today = date.today()
    if value > today:
        raise ValidationError('Purchase_Date cannot be in the future.')

class Member_Registration(models.Model):
    Purchase_Date=models.DateField(help_text="Enter the date of purchase", validators=[no_future])

关于python - 验证datefield,以便它不会在Django中使用将来的日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49882526/

相关文章:

python - 用 python 读取巨大的 .txt 文件

python - 无法通过 PyPI 中的 pip 安装最新版本的软件包

python - Django 多对多过滤字段

python - 为什么 WSGI 配置文件找不到我的 Python 变量?

python-3.x - boolean 测试 : Python prints '1' or 'True'

python - Pycharm 和 sys.argv 参数

python - 使用 Python/sqlAlchemy 使用外键和另一列设置复合键

android - DRF(django-rest-framework)和TokenAuthentication,如何根据Token自动填充json字段?

python - Fandjango 的神秘问题

Python X轴最近点