[Django]-Django "default=timezone.now()" saves records using the "old" time of when the Django server starts

70👍

✅

Just ran into this last week for a field that had default=date.today(). If you remove the parentheses (in this case, try default=timezone.now) then you’re passing a callable to the model and it will be called each time a new instance is saved. With the parentheses, it’s only being called once when models.py loads.

25👍

Just set the parameter auto_now_add like this.

timestamp = models.DateTimeField(auto_now_add=True)

Update:

Please don’t use auto_now_add. It is not the recommended way, instead do this:

from django.utils import timezone

timestamp = models.DateTimeField(default=timezone.now)

0👍

You should set timezone.now without () to DateTimeField() as a default value as shown below. *Don’t set timezone.now() with () because the default date and time become when the Django server starts (Unchanged) and don’t set datetime.now because UTC is not saved correctly in database when TIME_ZONE = ‘UTC’ which is default in settings.py:

from django.utils import timezone
# Don't set "timezone.now()" and "datetime.now" ↓ 
timestamp = models.DateTimeField(default=timezone.now)

Leave a comment