0

I've got an app on heroku that is setting incorrect timestamps for new objects. I can't figure out why for the life of me.

What's happening:

  1. I'm submitting a form on the heroku-run website.

  2. Django view creates new object and saves

  3. models.py has "ts = models.DateTimeField(default = datetime.now(utc))" so it should be saving the utc timestamp at submission (which it does locally), but on heroku it saves the timestamp of when the server started.

Models.py:

class NewsArticle(models.Model):
    link = models.URLField(max_length = 2000)
    title = models.CharField(max_length = 300)
    img_path = models.CharField(null = True, max_length = 300)
    ts = models.DateTimeField(default = datetime.now(utc))
    user = models.ForeignKey(User)
    hostname = models.CharField(max_length = 300)
    deleted = models.BooleanField(default = False)

Views.py:

news_article = NewsArticle(...)
news_article.save()

print news_article.ts
print datetime.now(utc)
import sys
sys.stdout.flush()

Corresponding output in heroku logs (I restarted the Heroku server at 22:00:34 UTC):

2013-01-02T22:01:56+00:00 app[web.1]: 2013-01-02 22:00:34.746547+00:00
2013-01-02T22:01:56+00:00 app[web.1]: 2013-01-02 22:01:56.919520+00:00

And then again 15 minutes later:

2013-01-02T22:15:46+00:00 app[web.1]: 2013-01-02 22:00:34.746547+00:00
2013-01-02T22:15:46+00:00 app[web.1]: 2013-01-02 22:15:46.489815+00:00

Clearly something isn't right with the datetime.now(utc) call that's happening in models.py, but I'm not sure why. Does anyone have an idea?

Andrew Cross
  • 1,921
  • 2
  • 19
  • 32
  • 1
    My guess is that it's related to this: http://stackoverflow.com/questions/2771676/django-default-datetime-now-problem - so that each instance is launched isn't hanging around, and you have to explicitly make it get the time... – Jon Clements Jan 02 '13 at 22:39

1 Answers1

2

Your problem is likely in how you set your default. The following two sets of code are identical:

now_at_import = datetime.now(utc)
MyModel
  ...
  ts = models.DateTimeField(default = now_at_import)

#is exactly the same as
MyModel
  ...
  ts = models.DateTimeField(default = datetime.now(utc))

What you want instead is:

def get_utc_now():
  return datetime.now(utc)


MyModel
  ...
  ts = models.DateTimeField(default = get_utc_now)
Ted
  • 12,122
  • 4
  • 31
  • 39