2011/8/23 Josh Lusk <lus...@gmail.com>:
> Quickly into the development of a simple blogging application I
> stumbled upon a baffling problem.  My index's get function originally
> fetched all the posts in the 'posts' table and sent it a template:
>
> the class:
>
> class index:
>    def GET(self):
>        posts = db.select('posts')
>        for post in posts:
>            post.pubDate = date(post.pubDate)
>
>        return render.index(posts)
>
> the template:
> $def with (posts)
>
> <html>
> <head>
>    <title>My Blog</title>
> </head>
> <body>
> <h1>My Blog</h1>
> $for post in posts:
>    <div class="post">
>        <h2><a href="/posts/$post.slug">$post.title</a></h2>
>        <p>$post.content</p>
>        <span>$post.pubDate</span>
>    </div>
> </body>
> </html>
>
> as you can see, it also converts the timestamp (stored in pubDate)
> into a formatted date string ('day' of 'month', 'year') for all the
> posts.  With this for loop no posts show up on the index, just the
> title ('My Blog').  Without it, the index shows the entire post along
> with the unformatted timestamp.

That is because the return value of db.select is an iterator. Your for
loop consumed it, so the template is seeing an empty iterator. You
need to convert the results into a list to avoid this problem. The
returned iterator has a special `list` method to convert the iterator
into a list.

    posts = db.select('posts').list()

Or, you can just call the list function to make it a list.

    posts = list(db.select('posts'))

Anand

-- 
You received this message because you are subscribed to the Google Groups 
"web.py" group.
To post to this group, send email to webpy@googlegroups.com.
To unsubscribe from this group, send email to 
webpy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/webpy?hl=en.

  • [web... Josh Lusk
    • ... Anand Chitipothu
      • ... Leandro - ProfessionalIT - Soluções em Tecnologia da Informação .
        • ... Josh Lusk

Reply via email to