Skip to content

Instantly share code, notes, and snippets.

@wonderb0lt
Last active February 11, 2021 23:01
Show Gist options
  • Save wonderb0lt/10645080 to your computer and use it in GitHub Desktop.
Save wonderb0lt/10645080 to your computer and use it in GitHub Desktop.
Very basic MongoEngine pagination
from math import ceil
class Pagination:
def __init__(self, items, page, per_page, total_items):
self.items = items
self.page = page
self.total_items = total_items
self.per_page = per_page
self.num_pages = int(ceil(total_items / float(per_page)))
@property
def has_next(self):
return self.page < self.num_pages
@property
def has_prev(self):
return self.page > 1
@property
def next_page(self):
return self.page + 1
@property
def prev_page(self):
return self.page - 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,
total_items=queryset.count())
{# 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>
</li>
{% for i in range(1, pagination.num_pages) %}
<li {% if products.page == i %}class="active"{% endif %}>
<a href="{{ url_for(destination) }}?page={{ i }}">{{ i }}</a>
</li>
{% endfor %}
<li {% if not pagination.has_next %}class="disabled"{% endif %}>
<a href="{{ url_for(destination) }}?page={{ pagination.next_page }}">&raquo;</a>
</li>
</ul>
{% endif %}
{% endmacro %}
@eddiegreysherman
Copy link

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