2010-09-29 22 views
2

我在GAE上使用Tornado框架(Python)。對於整個MVC概念和GAE,我還是一個新手......並且有一段時間試圖找出如何做到這一點。試圖格式化Google App Engine DateTimeProperty模板

我有一個表(模型)與字段用戶,文本,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) 

UPDATE:

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' object has no attribute 'text'

回答

2

假設您正在使用Tornado的template模塊,它包含日期時間模塊。我沒有使用過龍捲風的模板模塊,但你應該能夠使用:

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個實體來提高性能,而不是以較小批量抓取它們。

+0

太棒了。兩種方式都適合我。謝謝! – TylerW 2010-10-01 16:51:37

+0

Doh,我撒謊!我想我得到了第二部分工作,但我錯了。我得到「AttributeError:'字典'對象沒有屬性'文本'」 – TylerW 2010-10-06 00:05:08

+0

你能發佈你在處理程序和模板中使用的實際代碼嗎? – 2010-10-06 03:43:56