[Fixed]-How can I set bounds for a Django Model DateField?

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.

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])

Leave a comment