3

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.

Darwin Tech
  • 18,449
  • 38
  • 112
  • 187
  • I'm just wondering... is there any reason why you are not using auto_now and auto_now_add available for [DateField and DateTimeField](https://docs.djangoproject.com/en/dev/ref/models/fields/#datefield) – César Oct 31 '12 at 19:55
  • I read that it was not a very good implementation: http://www.benspaulding.us/weblog/2008/aug/02/auto_now_add-evil/, http://stackoverflow.com/questions/1737017/django-auto-now-and-auto-now-add – Darwin Tech Oct 31 '12 at 19:58

2 Answers2

4

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)
rantanplan
  • 7,283
  • 1
  • 24
  • 45
0

What I did to store now on creation, was use the default attribute of the DateTimeField, and Django's now() wrapper like so:

from django.utils import timezone

ctime = models.DateTimeField(default=timezone.now)

Please note that this date is in UTC timezone, if you require some other time zone to be set, wrap timezone.now in a lambda that calls localtime()

tutuDajuju
  • 10,307
  • 6
  • 65
  • 88