0

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?

atropa belladona
  • 474
  • 6
  • 25
  • [Your answer of question in this site](https://stackoverflow.com/questions/65658116/django-3-dynamic-default-value-in-model) – M.J.GH.PY Aug 26 '22 at 19:19

1 Answers1

2

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

nigel239
  • 1,485
  • 1
  • 3
  • 23
  • That looks great. But is there any way to handle it thru the Django DateField default argument? – atropa belladona Aug 26 '22 at 19:00
  • It has a problem, that will alter the date value every time we save the object. Like if we save the object date validity would be 2 Sep but if again we save the object tomorrow that would be 3 Sep. And that's not the accurate. – atropa belladona Aug 26 '22 at 19:03
  • 1
    @atropabelladona edited my answer to fit your needs. It does not set a new date every time, since the date field will already be populated. There was an `if` in place to check against this. – nigel239 Aug 26 '22 at 19:03
  • 1
    Yeah, Correct. I should do that way to handle that. – atropa belladona Aug 26 '22 at 19:05
  • 2
    In get_default_date() datetime.date.now() is not accurate. Because type object 'datetime.date' has no attribute 'now' That should be `datetime.date.today()` – Faisal Nazik Aug 26 '22 at 19:16