How can my django model DateField add 30 days to the provided value?

dotty picture dotty · Feb 4, 2010 · Viewed 43.6k times · Source

as the title suggests. I want to add 30 days to the DateField field. This is auto populated on creation of record using auto_now_add=True

Any ideas how to go about doing this?

Thanks

Answer

Simanas picture Simanas · Mar 8, 2013

There is no need to implement custom save method.

Also doing this default=datetime.now()+timedelta(days=30) is absolutely wrong! It gets evaluated when you start your instance of django. If you use apache it will probably work, because on some configurations apache revokes your django application on every request, but still you can find you self some day looking through out your code and trying to figure out why this get calculated not as you expect.

The right way of doing this is to pass a callable object to default argument. It can be a datetime.today function or your custom function. Then it gets evaluated every time you request a new default value.

def get_deadline():
    return datetime.today() + timedelta(days=20)

class Bill(models.Model):
    name = models.CharField(max_length=50)
    customer = models.ForeignKey(User, related_name='bills')
    date = models.DateField(default=datetime.today)
    deadline = models.DateField(default=get_deadline)