How to Properly Set a Default Value for a DateTimeField in Django

It is pretty common to have database fields to track the created and updated dates for objects in your model.  But how do you make sure that every time a new object is created they receive the current date and time?  That’s easy: just set the default option for your DateTimeField, such as

created_date = models.DateTimeField('date created',

That’s exactly what I’ve done and while developing with Django’s internal development server it works great!  Then I deployed my project to production which uses Apache with mod_wsgi and I noticed that the timestamps were wrong.  They seemed to coincide with when I had restarted Apache.  I googled things like “django datetime incorrect” and found other people with the same problem.  Some people resorted to overriding the save method, while others created database triggers to update with the current date and time on insert.  I didn’t think I should have to override the save method for something like this and I certainly didn’t want to start creating database triggers (I use Django to keep all of my logic in one place and abstract away my database!).

After doing some more research, it turns out that while I had read the manual, I didn’t understand the manual.  Referring to the Django docs for the default field option for models

The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.

you can see that you can either pass a value or callable object.  I thought that I was telling Django to evaluate the current time every time a new object was created, but I wasn’t.  What instead was happening was was being evaluated when the class was first instantiated (when the web server was restarted!) and that value was being reused every time a new object was created.  I needed to instead pass a callable object that would return the current date and time whenever a new object was created.

I updated my code from this

created_date = models.DateTimeField('date created',

to this

created_date = models.DateTimeField('date created',

Note that is evaluated only once when the class is instantiated and is a callable object that is evaluated each time a new object is created.  Including the parenthesis executes the function and passes the result while excluding the parenthesis passes the function itself.  This was a good lesson to learn and will definitely help me with my future Django coding.  Hopefully this tidbit helps someone else as well.

5 Responses to “How to Properly Set a Default Value for a DateTimeField in Django”

Leave a Reply