Any field with the
auto_now attribute set will also inherit
editable=False and therefore will not show up in the admin panel. There has been talk in the past about making the
auto_now_add arguments go away, and although they still exist, I feel you’re better off just using a custom
So, to make this work properly, I would recommend not using
auto_now_add and instead define your own
save() method to make sure that
created is only updated if
id is not set (such as when the item is first created), and have it update
modified every time the item is saved.
I have done the exact same thing with other projects I have written using Django, and so your
save() would look like this:
from django.utils import timezone
created = models.DateTimeField(editable=False)
modified = models.DateTimeField()
def save(self, *args, **kwargs):
''' On save, update timestamps '''
if not self.id:
self.created = timezone.now()
self.modified = timezone.now()
return super(User, self).save(*args, **kwargs)
Hope this helps!
Edit in response to comments:
The reason why I just stick with overloading
save() vs. relying on these field arguments is two-fold:
- The aforementioned ups and downs with their reliability. These arguments are heavily reliant on the way each type of database that Django knows how to interact with treats a date/time stamp field, and seems to break and/or change between every release. (Which I believe is the impetus behind the call to have them removed altogether).
- The fact that they only work on DateField, DateTimeField, and TimeField, and by using this technique you are able to automatically populate any field type every time an item is saved.
datetime.datetime.now(), because it will return a TZ-aware or naive
datetime.datetime object depending on
To address why the OP saw the error, I don’t know exactly, but it looks like
created isn’t even being populated at all, despite having
auto_now_add=True. To me it stands out as a bug, and underscores item #1 in my little list above:
auto_now_add are flaky at best.