2013-04-04 66 views
8

我有一个小瓶的应用这使得博客文章:瓶mongoengine分页

views.py:

class ListView(MethodView): 

    def get(self, page=1): 
     posts = Post.objects.all() 
     return render_template('posts/list.html', posts=posts) 

这一切都不错,但我想分页添加到posts对象。看看project docs,我看到有一个分页类。

所以,我想这一点:

class ListView(MethodView): 

    def get(self, page=1): 
     posts = Post.objects.paginate(page=page, per_page=10) 
     return render_template('posts/list.html', posts=posts) 

但现在我得到一个错误:

TypeError: 'Pagination' object is not iterable 

那么,如何遍历我的模板posts

任何帮助非常感谢。

+1

什么是你的温度后期代码?你可以分享吗? – codegeek 2013-04-04 23:50:07

回答

8

Pagination对象有一个items list它将包含mongoengine文档对象(在您的情况下为Post对象)。该列表可迭代显示文档。

例如,在您的模板:

{% for post in posts.items %} 
    {{ post.title }} 
    {{ post.content }} 
{% endfor %} 

获得实际的页码的分页链接,使用iter_pages()

<div id="pagination-links"> 
    {% for page in posts.iter_pages() %} 
     {{ page }} 
    {% endfor %} 
</div> 

无论是documentationgithub link above,有一个更好的例子分页链接:

{% macro render_pagination(pagination, endpoint) %} 
    <div class=pagination> 
     {%- for page in pagination.iter_pages() %} 
      {% if page %} 
       {% if page != pagination.page %} 
        <a href="{{ url_for(endpoint, page=page) }}">{{ page }}</a> 
       {% else %} 
        <strong>{{ page }}</strong> 
       {% endif %} 
      {% else %} 
       <span class=ellipsis>…</span> 
      {% endif %} 
     {%- endfor %} 
    </div> 
{% endmacro %} 
+0

更新了github链接以反映最新的烧瓶 - mongoengine发布 – 2013-05-09 13:12:57