For Django 1.1.
I have this in my models.py:
class User(models.Model):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
When updating a row I get:
[Sun Nov 15 02:18:12 2009] [error] /home/ptarjan/projects/twitter-meme/django/db/backends/mysql/base.py:84: Warning: Column 'created' cannot be null
[Sun Nov 15 02:18:12 2009] [error] return self.cursor.execute(query, args)
The relevant part of my database is:
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
Is this cause for concern?
Side question: in my admin tool, those two fields aren't showing up. Is that expected?
Based on what I've read and my experience with Django so far, auto_now_add is buggy. I agree with jthanism --- override the normal save method it's clean and you know what's hapenning. Now, to make it dry, create an abstract model called TimeStamped:
And then, when you want a model that has this time-stampy behavior, just subclass:
If you want the fields to show up in admin, then just remove the
editable=False
optionBah... Not enough reputation to comment... But I wanted to point out that the opinion expressed in the accepted answer is somewhat outdated. According to more recent discussions (django bugs #7634 and #12785), auto_now and auto_now_add are not going anywhere, and even if you go to the original discussion, you'll find strong arguments against the RY (as in DRY) in custom save methods.
A better solution has been offered (custom field types), but didn't gain enough momentum to make it into django. You can write your own in three lines (it's Jacob Kaplan-Moss' suggestion).
As for your Admin display, see this answer.
Note: auto_now and auto_now_add are set to editable=False by default, which is why this applies.
You can use
timezone.now()
for created andauto_now
for modified:If you are using a custom primary key instead of the default
auto- increment int
,auto_now_add
will lead to a bug.Here is the code of Django's default DateTimeField.pre_save with
auto_now
andauto_now_add
:I am not sure what the parameter
add
is. I hope it will some thing like:Talking about a side question: if you want to see this fields in admin (though, you won't be able to edit it), you can add
readonly_fields
to your admin class.Well, this applies only to latest Django versions (I believe, 1.3 and above)
auto_now=True
didn't work for me in Django 1.4.1, but the below code saved me. It's for timezone aware datetime.