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.http import urlquote
8 from django.utils.safestring import mark_safe
9 from django.utils.html import strip_tags, escape
10 from forum.utils.html import sanitize_html
13 def generate_uri(querydict, exclude=None):
16 for k, l in querydict.iterlists():
17 if (not exclude) or (not k in exclude):
18 all += ["%s=%s" % (k, urlquote(strip_tags(v))) for v in l]
22 class SortBase(object):
23 def __init__(self, label, description=''):
25 self.description = description
27 class SimpleSort(SortBase):
28 def __init__(self, label, order_by, description=''):
29 super(SimpleSort, self) .__init__(label, description)
30 self.order_by = order_by
32 def _get_order_by(self):
33 return isinstance(self.order_by, (list, tuple)) and self.order_by or [self.order_by]
35 def apply(self, objects):
36 return objects.order_by(*self._get_order_by())
38 class PaginatorContext(object):
39 visible_page_range = 5
40 outside_page_range = 1
44 def __init__(self, id, sort_methods=None, default_sort=None, force_sort = None,
45 pagesizes=None, default_pagesize=None, prefix=''):
49 self.sort_methods = SortedDict(data=sort_methods)
52 default_sort = sort_methods[0][0]
54 self.default_sort = default_sort
60 self.has_pagesize = True
61 self.pagesizes = pagesizes
63 if not default_pagesize:
64 self.default_pagesize = pagesizes[int(math.ceil(float(len(pagesizes)) / 2)) - 1]
66 self.default_pagesize = default_pagesize
68 self.has_pagesize = False
70 self.force_sort = force_sort
73 def preferences(self, request):
74 if request.user.is_authenticated():
75 if request.user.prop.pagination:
76 preferences = request.user.prop.pagination.get(self.id, {})
80 preferences = request.session.get('paginator_%s%s' % (self.prefix, self.id), {})
84 def set_preferences(self, request, preferences):
85 if request.user.is_authenticated():
86 all_preferences = request.user.prop.pagination or {}
87 all_preferences[self.id] = preferences
88 request.user.prop.pagination = all_preferences
90 request.session['paginator_%s%s' % (self.prefix, self.id)] = preferences
92 def pagesize(self, request, session_prefs=None):
94 session_prefs = self.preferences(request)
98 if request.GET.get(self.PAGESIZE, None):
100 pagesize = int(request.GET[self.PAGESIZE])
102 logging.error('Found invalid page size "%s", loading %s, refered by %s' % (
103 request.GET.get(self.PAGESIZE, ''), request.path, request.META.get('HTTP_REFERER', 'UNKNOWN')
107 session_prefs[self.PAGESIZE] = pagesize
109 pagesize = session_prefs.get(self.PAGESIZE, self.default_pagesize)
111 if not pagesize in self.pagesizes:
112 pagesize = self.default_pagesize
118 def page(self, request):
120 return int(request.GET.get(self.PAGE, "1").strip())
122 logging.error('Found invalid page number "%s", loading %s, refered by %s' % (
123 request.GET.get(self.PAGE, ''), request.path, request.META.get('HTTP_REFERER', 'UNKNOWN')
127 def sort(self, request, session_prefs=None):
128 if not session_prefs:
129 session_prefs = self.preferences(request)
132 sticky = request.user.is_authenticated() and request.user.prop.preferences and request.user.prop.preferences.get('sticky_sorts', False)
135 if request.GET.get(self.SORT, None):
136 sort = request.GET[self.SORT]
139 session_prefs[self.SORT] = sort
141 sort = self.force_sort or (sticky and session_prefs.get(self.SORT, None)) or self.default_sort
143 if not sort in self.sort_methods:
144 sort = self.default_sort
148 def sorted(self, objects, request, session_prefs=None):
149 sort = self.sort(request, session_prefs)
152 objects = self.sort_methods[sort].apply(objects)
158 return self.prefix and "%s_%s" % (self.prefix, _('pagesize')) or _('pagesize')
162 return self.prefix and "%s_%s" % (self.prefix, _('page')) or _('page')
166 return self.prefix and "%s_%s" % (self.prefix, _('sort')) or _('sort')
168 page_numbers_template = template.loader.get_template('paginator/page_numbers.html')
169 page_sizes_template = template.loader.get_template('paginator/page_sizes.html')
170 sort_tabs_template = template.loader.get_template('paginator/sort_tabs.html')
172 def paginated(request, paginators, tpl_context):
173 if len(paginators) == 2 and isinstance(paginators[0], basestring):
174 paginators = (paginators,)
176 for list_name, context in paginators:
177 tpl_context[list_name] = _paginated(request, tpl_context[list_name], context)
181 def _paginated(request, objects, context):
182 session_prefs = context.preferences(request)
184 pagesize = context.pagesize(request, session_prefs)
185 page = context.page(request)
186 sort, objects = context.sorted(objects, request, session_prefs)
188 paginator = Paginator(objects, pagesize)
191 page_obj = paginator.page(page)
193 logging.error('Found invalid page number "%s", loading %s, refered by %s' % (
194 request.GET.get(context.PAGE, ''), request.path, request.META.get('HTTP_REFERER', 'UNKNOWN')
198 if context.base_path:
199 base_path = context.base_path
201 base_path = request.path
202 get_params = generate_uri(request.GET, (context.PAGE, context.PAGESIZE, context.SORT))
205 base_path += "?" + get_params
207 url_joiner = "?" in base_path and "&" or "?"
211 object_list = page_obj.object_list
213 if hasattr(object_list, 'lazy'):
214 return object_list.lazy()
216 paginator.page = get_page()
218 total_pages = paginator.num_pages
222 total_pages = paginator.num_pages
224 has_previous = page > 1
225 has_next = page < total_pages
227 range_start = page - context.visible_page_range / 2
228 range_end = page + context.visible_page_range / 2
231 range_end = context.visible_page_range
234 if range_end > total_pages:
235 range_start = total_pages - context.visible_page_range + 1
236 range_end = total_pages
243 url_builder = lambda n: mark_safe("%s%s%s=%s&%s=%s" % (base_path, url_joiner, context.SORT, sort, context.PAGE, n))
245 url_builder = lambda n: mark_safe("%s%s%s=%s" % (base_path, url_joiner, context.PAGE, n))
247 if range_start > (context.outside_page_range + 1):
248 page_numbers.append([(n, url_builder(n)) for n in range(1, context.outside_page_range + 1)])
249 page_numbers.append(None)
250 elif range_start > 1:
251 page_numbers.append([(n, url_builder(n)) for n in range(1, range_start)])
253 page_numbers.append([(n, url_builder(n)) for n in range(range_start, range_end + 1)])
255 if range_end < (total_pages - context.outside_page_range):
256 page_numbers.append(None)
257 page_numbers.append([(n, url_builder(n)) for n in range(total_pages - context.outside_page_range + 1, total_pages + 1)])
258 elif range_end < total_pages:
259 page_numbers.append([(n, url_builder(n)) for n in range(range_end + 1, total_pages + 1)])
261 return page_numbers_template.render(template.Context({
262 'has_previous': has_previous,
263 'previous_url': has_previous and url_builder(page - 1) or None,
264 'has_next': has_next,
265 'next_url': has_next and url_builder(page + 1) or None,
267 'page_numbers': page_numbers
269 paginator.page_numbers = page_nums
271 paginator.page_numbers = ''
276 url_builder = lambda s: mark_safe("%s%s%s=%s&%s=%s" % (escape(base_path), url_joiner, context.SORT, sort, context.PAGESIZE, s))
278 url_builder = lambda s: mark_safe("%s%s%s=%s" % (escape(base_path), url_joiner, context.PAGESIZE, s))
280 sizes = [(s, url_builder(s)) for s in context.pagesizes]
282 return page_sizes_template.render(template.Context({
287 paginator.page_sizes = page_sizes
289 paginator.page_sizes = ''
293 url_builder = lambda s: mark_safe("%s%s%s=%s" % (escape(base_path), url_joiner, context.SORT, s))
294 sorts = [(n, s.label, url_builder(n), strip_tags(s.description)) for n, s in context.sort_methods.items()]
296 for name, label, url, descr in sorts:
297 paginator.__dict__['%s_sort_link' % name] = url
299 return sort_tabs_template.render(template.Context({
302 'sticky': session_prefs.get('sticky_sort', False)
304 paginator.sort_tabs = sort_tabs()
305 paginator.sort_description = mark_safe(context.sort_methods[sort].description)
306 paginator.current_sort = sort
308 paginator.sort_tabs = paginator.sort_description = ''
309 paginator.current_sort = ''
311 context.set_preferences(request, session_prefs)
312 objects.paginator = paginator