Created
November 6, 2017 20:35
-
-
Save dlyapun/f7f47b50f80f5c004c212c8b710227e3 to your computer and use it in GitHub Desktop.
Pagination Django Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
PAGINATE_BY = 9 | |
ALL_PAGES = 'all pages' | |
def paginator(page, data_objects, objects_count=None): | |
paginate = PAGINATE_BY | |
page = int(page) | |
next = PAGINATE_BY * page | |
previous = next - PAGINATE_BY | |
num_pages = int(math.ceil(objects_count / float(PAGINATE_BY))) # 7 | |
data = {'number': page, | |
'num_pages': num_pages, | |
'page_range': [page for page in xrange(1, num_pages + 1)]} | |
FIRST_PAGE = 1 | |
LAST_PAGE = num_pages | |
if data['number'] == FIRST_PAGE: | |
data['has_next'] = True | |
data['has_previous'] = False | |
data['next_page_number'] = data['number'] + 1 | |
data['data'] = data_objects[:PAGINATE_BY] | |
elif data['number'] == LAST_PAGE: | |
data['data'] = data_objects[previous:next] | |
data['has_next'] = False | |
data['has_previous'] = True | |
data['previous_page_number'] = data['number'] - 1 | |
else: | |
data['data'] = data_objects[previous:next] | |
data['has_next'] = True | |
data['has_previous'] = True | |
data['next_page_number'] = data['number'] + 1 | |
data['previous_page_number'] = data['number'] - 1 | |
return data | |
{% if articles.num_pages != 0 %} | |
<div class="pagination post-item-quant"> | |
<div class="post-item-quant-body"> | |
{% if articles.has_previous %} | |
<div class="post-item-like" > | |
<a href="?page={{ articles.previous_page_number }}"> | |
<button style="float: left !important;"> | |
Previous page | |
</button></a> | |
</div> | |
{% endif %} | |
{% for index in articles.page_range %} | |
{% if articles.number == index %} | |
<div class="post-item-like"> | |
<button disabled="disabled" style="padding: 0px 16px 0px 16px; margin-left: 2px; margin-right: 2px; background-color: #6a7277"> | |
{{ articles.number }} | |
</button> | |
</div> | |
{% else %} | |
<div class="post-item-like"> | |
<a href="?page={{ index }}"> | |
<button style="padding: 0px 16px 0px 16px; margin-left: 2px; margin-right: 2px;"> | |
{{ index }} | |
</button> | |
</a> | |
</div> | |
{% endif %} | |
{% endfor %} | |
{% if articles.has_next %} | |
<div class="post-item-like"> | |
<a href="?page={{ articles.next_page_number }}"> | |
<button style="float: right !important;"> | |
Next page | |
</button></a> | |
</div> | |
{% endif %} | |
</div> | |
</div> | |
{% endif %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment