Django Datetimefield Auto_now_add Not Working
Solution 1:
As far as I know, best practice for default datetimes is to use the following:
created_datetime = models.DateTimeField(default=datetime.datetime.now)
Don't forget to import datetime
Solution 2:
I had this and it really confused me for ages.
Turned out that my model had a custom primary key, and it was due to a bug not setting it when constructing some test objects.
The first time this worked fine as auto_now_add
set created_at
. The second time it didn't as the object with a null primary key already existed, so it was doing an update. And it tried to set that to created_at
null, which wasn't allowed in my model.
So worth checking if you end up on this question with the error "in my application it is raising a exception that created_datetime field cannot be null", that that could be caused by not setting a primary key correctly.
The solution was for me to correctly set a primary key.
Solution 3:
You can do something like this
created_datetime = models.DateTimeField(auto_now_add=True, auto_now=False)
Solution 4:
The following way is in the "part1" of django documentation
from django.utils importtimezonep= Poll(question="What's new?", pub_date=timezone.now())
Post a Comment for "Django Datetimefield Auto_now_add Not Working"