How to set a default date dynamically in DateField

I'm trying to add a field today + 7 days as a default value in the Django DateField.

That's How I'm doing.

date_validity = models.DateField(default=datetime.date.today() + timedelta(days=7))

But that's giving me the problem One thing is Field is being altered every time when we run makemigrations/migrate command however we are not making any changes. How can I set that up accurately?

Add the following on the model to set a date when none is given/set.

def save(self, *args, **kwargs)
    if not self.date_validity:
        self.date_validity = datetime.date.today() + timedelta(days=7)
    super().save(*args,**kwargs) # Or super(MyModel, self).save(*args,**kwargs) # for older python versions.

To get the date for the field.

def get_default_date():
    return datetime.date.now() + timedelta(days = 7)

And then in the field:

date_validity = models.DateField(default=get_default_date)

Possible duplicate of:

https://stackoverflow.com/a/2771701/18020941

Back to Top