Skip to content

Instantly share code, notes, and snippets.

@wonderb0lt wonderb0lt/logic.py
Last active Aug 25, 2017

Embed
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
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

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.