Reputation: 2786
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.
Thanks!
Upvotes: 0
Views: 237
Reputation: 309069
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.
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])
Upvotes: 1