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)
- [Django]-Accelerate bulk insert using Django's ORM?
- [Django]-Listing objects from ManyToManyField
- [Django]-Is there a datetime ± infinity?
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)
- [Django]-Execute code when Django starts ONCE only?
- [Django]-How to set css class of a label in a django form declaration?
- [Django]-How to Unit test with different settings in Django?