In my model
:
在我的模型中:
birth_date = models.DateField(verbose_name='D.O.B')
How can I set bounds for this, such as:
如何为此设置界限,例如:
01-01-1990 to (current date - 18 years)
I'm assuming there's a way to set this in the model so it's included by default in forms, but I've never used dates in a project before, so I'm not sure how this is done.
我假设有一种方法可以在模型中设置它,所以它默认包含在表单中,但我之前从未在项目中使用过日期,所以我不确定这是怎么做的。
It would be useful to know how to do this with DateTimeField
and TimeField
if it isn't the same.
如果它不相同,知道如何使用DateTimeField和TimeField这将是有用的。
Thanks!
谢谢!
1 个解决方案
#1
1
DateTimeField
and TimeField
do not have options to set lower and upper bounds. However, it is possible to write validators for any type of field.
DateTimeField和TimeField没有设置下限和上限的选项。但是,可以为任何类型的字段编写验证器。
A validator to check the date of birth would look something like:
检查出生日期的验证员将类似于:
from datetime import date
from django.core.exceptions import ValidatonError
def validate_dob(value):
"""Makes sure that date is been 1990-01-01 and 18 years ago."""
today = date.today()
eighteen_years_ago = today.replace(year=today.year - 18)
if not date(1990, 1, 1) <= value <= eighteen_years_ago:
raise ValidationError("Date must be between %s and %s" % (date(1990,1,1,), eighteen_years_ago)
Then use your validator in your model field.
然后在模型字段中使用验证器。
birth_date = models.DateField(verbose_name='D.O.B', validators=[validate_dob])
#1
1
DateTimeField
and TimeField
do not have options to set lower and upper bounds. However, it is possible to write validators for any type of field.
DateTimeField和TimeField没有设置下限和上限的选项。但是,可以为任何类型的字段编写验证器。
A validator to check the date of birth would look something like:
检查出生日期的验证员将类似于:
from datetime import date
from django.core.exceptions import ValidatonError
def validate_dob(value):
"""Makes sure that date is been 1990-01-01 and 18 years ago."""
today = date.today()
eighteen_years_ago = today.replace(year=today.year - 18)
if not date(1990, 1, 1) <= value <= eighteen_years_ago:
raise ValidationError("Date must be between %s and %s" % (date(1990,1,1,), eighteen_years_ago)
Then use your validator in your model field.
然后在模型字段中使用验证器。
birth_date = models.DateField(verbose_name='D.O.B', validators=[validate_dob])