尝试将Google App Engine DateTimeProperty格式化为模板

时间:2010-09-29 22:45:38

标签: python google-app-engine

我在GAE上使用Tornado框架(Python)。我仍然对整个MVC概念和GAE都不熟悉......而且还有一段时间试图弄清楚如何做到这一点。

我有一个表(模型)帖子,其中包含字段user,text,creation_date。

我拉取代码中的所有帖子,然后将其发送到模板。我想格式化creation_date字段,使其格式更好一些。像M-d-Y这样的东西。我知道我使用strptime或strftime格式化creation_date。但在将帖子发送到模板之前,我不确定该怎么做。

以下是我用来获取帖子并将其发送到模板的内容......

class HomeHandler(BaseHandler):
    def get(self):
        posts = Post.all()
        posts.order("-creation_date")
        self.render('home.html', posts=posts)

更新:

posts = Post.all().order("-creation_date").fetch(50)
posts = [{'text': post.text} for post in posts]
for post in posts:
        print post.text

我收到错误消息:

  

AttributeError:'dict'对象没有属性'text'

1 个答案:

答案 0 :(得分:2)

假设您正在使用Tornado的template模块,它包含日期时间模块。我没有使用过Tornado的模板模块,但您应该可以使用:

entity.datetime_property.strftime('%m-%d-%y')

如果您想在将模型发送到模板之前处理模型,请尝试以下操作:

class HomeHandler(BaseHandler):
  def get(self):
    posts = Post.all().order("-creation_date").fetch(50)
    posts = [{'author': post.author,
              'subject': post.subject,
              'date': post.date} for post in posts]
    self.render('home.html', posts=posts)

在您的模板中,帖子将是包含作者,主题和日期字段的词典列表。

使用fetch来限制您返回的帖子数量;它可以通过一次抓取(最多)50个实体来提高性能,而不是以较小的批次抓取它们。

相关问题