How to set a default date dynamically in DateField

Question:

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?

Asked By: atropa belladona

||

Answers:

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.today() + 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

Answered By: nigel239
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.