TylerW
TylerW

Reputation: 1553

Trying to format Google App Engine DateTimeProperty for template

I'm using the Tornado framework (Python) on GAE. I'm still kind of new to the whole MVC concept and GAE... and having a dang of a time trying to figure out how to do this.

I have a table (model) Post with the fields user, text, creation_date.

I pull all the posts in the code and then send it to the template. I want to format the creation_date field so it's formatted a bit nicer. Something like M-d-Y. I know I use strptime or strftime to format the creation_date. But I'm not sure how to do it before I send posts to the template.

Here is what I use to get the posts and send it to the template...

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

Error message I get:

AttributeError: 'dict' object has no attribute 'text'

Upvotes: 2

Views: 1741

Answers (1)

Robert Kluin
Robert Kluin

Reputation: 8292

Assuming you are using Tornado's template module, it includes the datetime module. I have not used Tornado's template module, but you should be able to use:

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

If you want to process your models before sending them to the template try something like:

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)

Within your template posts will be a list of dictionaries containing the fields author, subject, and date.

Use fetch to limit the number of posts you return; it will improve performance by grabbing (up to) 50 entities at once instead of grabbing them in smaller batches.

Upvotes: 2

Related Questions