3

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)
vvAve
  • 177
  • 1
  • 3
  • 13

2 Answers2

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
  • 6,414
  • 10
  • 59
  • 93
  • According to [the doc](https://docs.djangoproject.com/en/2.0/ref/validators/#writing-validators), shouldn't a validator raise a `ValidationError`? – vmonteco Apr 24 '18 at 13:27
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.