validation - How can I set bounds for a Django Model DateField? -
in model
:
birth_date = models.datefield(verbose_name='d.o.b')
how can set bounds this, such as:
01-01-1990 (current date - 18 years)
i'm assuming there's way set in model it's included default in forms, i've never used dates in project before, i'm not sure how done.
it useful know how datetimefield
, timefield
if isn't same.
thanks!
datetimefield
, timefield
not have options set lower , upper bounds. however, possible write validators type of field.
a validator check date of birth like:
from datetime import date django.core.exceptions import validatonerror def validate_dob(value): """makes sure date been 1990-01-01 , 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 between %s , %s" % (date(1990,1,1,), eighteen_years_ago)
then use validator in model field.
birth_date = models.datefield(verbose_name='d.o.b', validators=[validate_dob])
Comments
Post a Comment