Skip to content

Instantly share code, notes, and snippets.

@wonderb0lt wonderb0lt/
Last active Aug 25, 2017

What would you like to do?
Very basic MongoEngine pagination
from math import ceil
class Pagination:
def __init__(self, items, page, per_page, total_items):
self.items = items = page
self.total_items = total_items
self.per_page = per_page
self.num_pages = int(ceil(total_items / float(per_page)))
def has_next(self):
return < self.num_pages
def has_prev(self):
return > 1
def next_page(self):
return + 1
def prev_page(self):
return - 1
def paginate(queryset, page=1, per_page=30):
skip = (page-1)*per_page
limit = per_page
return Pagination(queryset.limit(limit).skip(skip), page=page, per_page=per_page,
{# Jinja2 macro #}
{% macro paginate(pagination, destination, small=False) %}
{% if pagination.num_pages > 1 %}
<ul class="pagination {% if small %}pagination-sm{% endif %}" id="pagination">
<li {% if not pagination.has_prev %}class="disabled"{% endif %}>
<a href="{{ url_for(destination) }}?page={{ pagination.prev_page }}">&laquo;</a>
{% for i in range(1, pagination.num_pages) %}
<li {% if == i %}class="active"{% endif %}>
<a href="{{ url_for(destination) }}?page={{ i }}">{{ i }}</a>
{% endfor %}
<li {% if not pagination.has_next %}class="disabled"{% endif %}>
<a href="{{ url_for(destination) }}?page={{ pagination.next_page }}">&raquo;</a>
{% endif %}
{% endmacro %}

This comment has been minimized.

Copy link

eddiegreysherman commented Aug 25, 2017

Thanks for this. I was struggling to figure out how to do this. Also works with Flask-PyMongo...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.