[Django]-Django models.DateField prevent past

6👍

The correct way to do this is a validator. For example:

def validate_date(date):
    if date < timezone.now().date():
        raise ValidationError("Date cannot be in the past")

That function will determine whether a particular input value is acceptable, then you can add the validator to the model field like so:

date = models.DateField(null=True, blank=True, default=None, validators=[validate_date])
👤benwad

0👍

You can do a validation in forms.py file to make sure that the entered date is not older than the current date. So, even if someone tries to enter a older date the user would get an error. Hope it works for you.

Leave a comment