Django: Making the DateTimeField Default to Now

23 May 2012

If you've ever needed to make a DatetimeField to default to a current datetime value, but with the option to adjust it, you should do this:


Notice how we didn't call the function datetime.now().

Here you are actually passing in the function datetime.now itself, instead of evaluating the function with datetime.now() and making the default the result of that when the model is instantiated. Otherwise, you'll get a static datetime object as your default. This way it will be re-evaluated every time with the correct value.

If you need to do any arithmetic on the date, you can use a lambda function:
models.DateTimeField(default=lambda: datetime.now() + timedelta(days=3))

Likewise we are passing in a function to be re-evaluated every time.

Of course, it goes without saying if you want it to always be now, you can use :