This repository has been archived by the owner on Feb 28, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpaginator.py
75 lines (54 loc) · 2.42 KB
/
paginator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import math
from django.core.paginator import Paginator, Page
"""
Pagination classes for windowed/ranged pagination
"""
class WindowPaginator(Paginator):
def page(self, number, window=None):
"""
Returns a Page object for the given 1-based page number.
This is a copy of Paginator.page, but returning a WindowPage
instance instead of a Page one
"""
number = self.validate_number(number)
bottom = (number - 1) * self.per_page
top = bottom + self.per_page
if top + self.orphans >= self.count:
top = self.count
return WindowPage(self.object_list[bottom:top], number, self, window=window)
class WindowPage(Page):
def __init__(self, object_list, number, paginator, window=None):
"""
WindowPage object constructor
`window`
A number indicating how many page links you want to display in between the first and last pages.
Example: a value of '5' with a total of 30 pages, on page 14 would yield a page range of:
[1, None, 12, 13, 14, 15, 16, None, 30]
"""
super(WindowPage, self).__init__(object_list, number, paginator)
self.window = window
def _get_page_range(self):
if self.window and self.window + 2 < self.paginator.num_pages: # If a window is set, and that window plus the first and last pages is less than the total...
# Calculate lower and higher window limits
page_max = self.paginator.num_pages
offset = int(math.floor(float(self.window - 1) / 2))
lower = self.number - offset
higher = self.number + (self.window - offset)
if lower <= 2:
lower = 2
higher = 2 + self.window
elif higher >= page_max:
higher = page_max
lower = higher - self.window
# Build pages list
pages = [1]
if lower > 2:
pages.append(None)
pages.extend(range(lower, higher))
if higher < page_max - 1:
pages.append(None)
pages.append(page_max)
return pages
else:
return self.paginator._get_page_range()
page_range = property(_get_page_range)