Django can't auto save DateTimeFields

django, django-admin, django-models

Solution

First of all DateTimeField supports auto updating like this:

created = models.DateTimeField(editable=False, auto_now_add=True) # Only on creation
updated = models.DateTimeField(editable=False, auto_now=True)     # On every save

Secondly the RuntimeWarning you get, means that you have enabled in your settings.py timezone aware datetime objects e.g you will see the following:

USE_TZ = True

When you do that, you have to treat datetime objects differently, you have to pass explicitly a `tzinfo` value.

# install the `pytz` module through pip or whatnot
from pytz import timezone
import datetime
from django.utils.timezone import utc

now = datetime.datetime.utcnow().replace(tzinfo=utc)

# To show the time in Greece
athens = timezone('Europe/Athens')
print now.astimezone(athens)

For more info see the django docs and the pytz docs.

About the `coercing to Unicode:` error, try doing this:

def __unicode__(self):
    return unicode(self.id)

Problem

Hi I have a model like so: ``` from datetime import datetime class Project(models.Model): created = models.DateTimeField(editable=False) updated = models.DateTimeField(editable=False) product = models.ForeignKey('tool.product') module = models.ForeignKey('tool.module') model = models.ForeignKey('tool.model') zipcode = models.IntegerField(max_length=5) def save(self, **kwargs): if not self.id: self.created = datetime.now() self.updated = datetime.now() super(Project, self).save() def __unicode__(self): return self.id ``` However when I try to save a project I get: ``` coercing to Unicode: need string or buffer, long found ``` and from the runserver: ``` RuntimeWarning: DateTimeField received a naive datetime (2012-10-31 14:45:36.611622) while time zone support is active. ``` I'm not sure exactly what the problem is here but I'm assuming it has something to do with `timezone` getting in the way of saving the `DateTimeField`. Any help would be much appreciated.

Original source

Related problems