Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django models.DateField prevent past

I am looking for ways to prevent user from entering past dates in in django admin page. Something like this:

Django: How to set DateField to only accept Today & Future dates

My model looks like this:

class MyModel(models.Model):
    date = models.DateField(null=True, blank=True, default=None)
like image 620
vvAve Avatar asked Nov 25 '25 10:11

vvAve


1 Answers

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])
like image 57
benwad Avatar answered Nov 26 '25 22:11

benwad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!