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?
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 class User(models.Model): 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:
datetime.datetime.now(), because it will return a TZ-aware or naive
datetime.datetimeobject 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.
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).
from django.db import models from django.utils import timezone class AutoDateTimeField(models.DateTimeField): def pre_save(self, model_instance, add): return timezone.now() #usage created_at = models.DateField(default=timezone.now) updated_at = models.AutoDateTimeField(default=timezone.now)