Flask mongoengine pagination
flask, mongodb, mongoengine, python
Solution
The `Pagination` object has an `items` list which will contain the mongoengine document objects (in your case the `Post` objects). This list can be iterated through to display the documents.
For example, in your template:
{% for post in posts.items %}
{{ post.title }}
{{ post.content }}
{% endfor %}
To get the actual page numbers for pagination links, use `iter_pages()`:
<div id="pagination-links">
{% for page in posts.iter_pages() %}
{{ page }}
{% endfor %}
</div>
Both the documentation and the github link above, have a better example for pagination links:
{% 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 %}
Problem
I have a small Flask app which renders blog posts: views.py: ``` class ListView(MethodView): def get(self, page=1): posts = Post.objects.all() return render_template('posts/list.html', posts=posts) ``` This is all good, but I would like to add pagination to the `posts` object. Looking at the project docs, I see there is a pagination class. So I tried this: ``` 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) ``` But now I get an error: ``` TypeError: 'Pagination' object is not iterable ``` So how do I iterate through my `posts` in the template?