2 from django.utils.datastructures import SortedDict
3 from django import template
4 from django.core.paginator import Paginator, EmptyPage
5 from django.utils.translation import ugettext as _
6 from django.http import Http404
7 from django.utils.safestring import mark_safe
8 from django.utils.http import urlquote
11 class SimpleSort(object):
12 def __init__(self, label, order_by, description=''):
14 self.description = description
15 self.order_by = order_by
17 def apply(self, objects):
18 if isinstance(self.order_by, (list, tuple)):
19 return objects.order_by(*self.order_by)
21 return objects.order_by(self.order_by)
23 class DummySort(object):
24 def __init__(self, label, description=''):
26 self.description = description
28 def apply(self, objects):
32 class PaginatorContext(object):
33 visible_page_range = 5
34 outside_page_range = 1
38 def __init__(self, id, sort_methods=None, default_sort=None, force_sort = None,
39 pagesizes=None, default_pagesize=None, prefix=''):
43 self.sort_methods = SortedDict(data=sort_methods)
46 default_sort = sort_methods[0][0]
48 self.default_sort = default_sort
54 self.has_pagesize = True
55 self.pagesizes = pagesizes
57 if not default_pagesize:
58 self.default_pagesize = pagesizes[int(math.ceil(float(len(pagesizes)) / 2)) - 1]
60 self.default_pagesize = default_pagesize
62 self.has_pagesize = False
64 self.force_sort = force_sort
67 def preferences(self, request):
68 if request.user.is_authenticated():
69 if request.user.prop.pagination:
70 preferences = request.user.prop.pagination.get(self.id, {})
74 preferences = request.session.get('paginator_%s%s' % (self.prefix, self.id), {})
78 def set_preferences(self, request, preferences):
79 if request.user.is_authenticated():
80 all_preferences = request.user.prop.pagination or {}
81 all_preferences[self.id] = preferences
82 request.user.prop.pagination = all_preferences
84 request.session['paginator_%s%s' % (self.prefix, self.id)] = preferences
86 def pagesize(self, request, session_prefs=None):
88 session_prefs = self.preferences(request)
92 if request.GET.get(self.PAGESIZE, None):
94 pagesize = int(request.GET[self.PAGESIZE])
96 logging.error('Found invalid page size "%s", loading %s, refered by %s' % (
97 request.GET.get(self.PAGESIZE, ''), request.path, request.META.get('HTTP_REFERER', 'UNKNOWN')
101 session_prefs[self.PAGESIZE] = pagesize
103 pagesize = session_prefs.get(self.PAGESIZE, self.default_pagesize)
105 if not pagesize in self.pagesizes:
106 pagesize = self.default_pagesize
112 def page(self, request):
114 return int(request.GET.get(self.PAGE, 1))
116 logging.error('Found invalid page number "%s", loading %s, refered by %s' % (
117 request.GET.get(self.PAGE, ''), request.path, request.META.get('HTTP_REFERER', 'UNKNOWN')
121 def sort(self, request, session_prefs=None):
122 if not session_prefs:
123 session_prefs = self.preferences(request)
126 sticky = request.user.is_authenticated() and request.user.prop.preferences and request.user.prop.preferences.get('sticky_sorts', False)
129 if request.GET.get(self.SORT, None):
130 sort = request.GET[self.SORT]
133 session_prefs[self.SORT] = sort
135 sort = self.force_sort or (sticky and session_prefs.get(self.SORT, None)) or self.default_sort
137 if not sort in self.sort_methods:
138 sort = self.default_sort
142 def sorted(self, objects, request, session_prefs=None):
143 sort = self.sort(request, session_prefs)
146 objects = self.sort_methods[sort].apply(objects)
152 return self.prefix and "%s_%s" % (self.prefix, _('pagesize')) or _('pagesize')
156 return self.prefix and "%s_%s" % (self.prefix, _('page')) or _('page')
160 return self.prefix and "%s_%s" % (self.prefix, _('sort')) or _('sort')
162 page_numbers_template = template.loader.get_template('paginator/page_numbers.html')
163 page_sizes_template = template.loader.get_template('paginator/page_sizes.html')
164 sort_tabs_template = template.loader.get_template('paginator/sort_tabs.html')
166 def paginated(request, paginators, tpl_context):
167 if len(paginators) == 2 and isinstance(paginators[0], basestring):
168 paginators = (paginators,)
170 for list_name, context in paginators:
171 tpl_context[list_name] = _paginated(request, tpl_context[list_name], context)
175 def _paginated(request, objects, context):
176 session_prefs = context.preferences(request)
178 pagesize = context.pagesize(request, session_prefs)
179 page = context.page(request)
180 sort, objects = context.sorted(objects, request, session_prefs)
182 paginator = Paginator(objects, pagesize)
185 page_obj = paginator.page(page)
187 logging.error('Found invalid page number "%s", loading %s, refered by %s' % (
188 request.GET.get(context.PAGE, ''), request.path, request.META.get('HTTP_REFERER', 'UNKNOWN')
192 if context.base_path:
193 base_path = context.base_path
195 base_path = request.path
196 get_params = ["%s=%s" % (k, v) for k, v in request.GET.items() if not k in (context.PAGE, context.PAGESIZE, context.SORT)]
199 base_path += "?" + "&".join(get_params)
201 url_joiner = "?" in base_path and "&" or "?"
205 object_list = page_obj.object_list
207 if hasattr(object_list, 'lazy'):
208 return object_list.lazy()
210 paginator.page = get_page()
212 total_pages = paginator.num_pages
216 total_pages = paginator.num_pages
218 has_previous = page > 1
219 has_next = page < total_pages
221 range_start = page - context.visible_page_range / 2
222 range_end = page + context.visible_page_range / 2
225 range_end = context.visible_page_range
228 if range_end > total_pages:
229 range_start = total_pages - context.visible_page_range + 1
230 range_end = total_pages
237 url_builder = lambda n: mark_safe("%s%s%s=%s&%s=%s" % (base_path, url_joiner, context.SORT, sort, context.PAGE, n))
239 url_builder = lambda n: mark_safe("%s%s%s=%s" % (base_path, url_joiner, context.PAGE, n))
241 if range_start > (context.outside_page_range + 1):
242 page_numbers.append([(n, url_builder(n)) for n in range(1, context.outside_page_range + 1)])
243 page_numbers.append(None)
244 elif range_start > 1:
245 page_numbers.append([(n, url_builder(n)) for n in range(1, range_start)])
247 page_numbers.append([(n, url_builder(n)) for n in range(range_start, range_end + 1)])
249 if range_end < (total_pages - context.outside_page_range):
250 page_numbers.append(None)
251 page_numbers.append([(n, url_builder(n)) for n in range(total_pages - context.outside_page_range + 1, total_pages + 1)])
252 elif range_end < total_pages:
253 page_numbers.append([(n, url_builder(n)) for n in range(range_end + 1, total_pages + 1)])
255 return page_numbers_template.render(template.Context({
256 'has_previous': has_previous,
257 'previous_url': has_previous and url_builder(page - 1) or None,
258 'has_next': has_next,
259 'next_url': has_next and url_builder(page + 1) or None,
261 'page_numbers': page_numbers
263 paginator.page_numbers = page_nums
265 paginator.page_numbers = ''
270 url_builder = lambda s: mark_safe("%s%s%s=%s&%s=%s" % (base_path, url_joiner, context.SORT, sort, context.PAGESIZE, s))
272 url_builder = lambda s: mark_safe("%s%s%s=%s" % (base_path, url_joiner, context.PAGESIZE, s))
274 sizes = [(s, url_builder(s)) for s in context.pagesizes]
276 return page_sizes_template.render(template.Context({
281 paginator.page_sizes = page_sizes
283 paginator.page_sizes = ''
287 url_builder = lambda s: mark_safe("%s%s%s=%s" % (base_path, url_joiner, context.SORT, s))
288 sorts = [(n, s.label, url_builder(n), s.description) for n, s in context.sort_methods.items()]
290 return sort_tabs_template.render(template.Context({
293 'sticky': session_prefs.get('sticky_sort', False)
295 paginator.sort_tabs = sort_tabs()
297 paginator.sort_tabs = ''
299 context.set_preferences(request, session_prefs)
300 objects.paginator = paginator