'How to iterate pages for pagination if its more than certain number in Flask without SQLAlchemy?
I want to create pagination for my blog using Peewee instead of SQLAlchemy as I seen every tutorial on it, so I'm trying to use something different. I rarely see any tutorial on it. I updated a previous question but there were no responses so I decided to create a new post. Now I already manage to display the pages using range:
{% for page_num in range(1, pagination.get_page_count() + 1) %}
{% if pagination.get_page() == page_num %}
<a href="./?{{ request.args|clean_querystring('page', page=page_num) }}" class="btn btn-primary">{{ page_num }}</a>
{% else %}
<a href="./?{{ request.args|clean_querystring('page', page=page_num) }}" class="btn btn-outline-primary">{{ page_num }}</a>
{% endif %}
{% endfor %}
What I'm trying to do now is splitting the pages similar to SQLAlchemy "iter_pages" threshold:
Is there a way I could do this using range, or do I need to use something else?
Solution 1:[1]
You can fiddle around with something like this:
def get_page_range(page, total, show=5):
start = max((page - (show // 2)), 1)
stop = min(start + show, total) + 1
start = max(min(start, stop - show), 1)
return list(range(start, stop)[:show])
Example output for pages 1-10 where there are 10 total pages of results, and 5 buttons should be shown:
for i in range(1, 11):
print(i, get_page_range(i, 10, 5))
Output:
1 [1, 2, 3, 4, 5]
2 [1, 2, 3, 4, 5]
3 [1, 2, 3, 4, 5]
4 [2, 3, 4, 5, 6]
5 [3, 4, 5, 6, 7]
6 [4, 5, 6, 7, 8]
7 [5, 6, 7, 8, 9]
8 [6, 7, 8, 9, 10]
9 [6, 7, 8, 9, 10]
10 [6, 7, 8, 9, 10]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | coleifer |


