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.utils.html import escape
7 from django.http import Http404
8 from django.utils.http import urlquote
9 from django.utils.safestring import mark_safe
10 from django.utils.html import strip_tags, escape
11 from forum.utils.html import sanitize_html
14 def generate_uri(querydict, exclude=None):
17 for k, l in querydict.iterlists():
18 if (not exclude) or (not k in exclude):
19 all += ["%s=%s" % (k, escape(strip_tags(v))) for v in l]
23 class SortBase(object):
24 def __init__(self, label, description=''):
26 self.description = description
28 class SimpleSort(SortBase):
29 def __init__(self, label, order_by, description=''):
30 super(SimpleSort, self) .__init__(label, description)
31 self.order_by = order_by
33 def _get_order_by(self):
34 return isinstance(self.order_by, (list, tuple)) and self.order_by or [self.order_by]
36 def apply(self, objects):
38 return objects.order_by(*self._get_order_by())
42 class PaginatorContext(object):
43 visible_page_range = 5
44 outside_page_range = 1
48 def __init__(self, id, sort_methods=None, default_sort=None, force_sort = None,
49 pagesizes=None, default_pagesize=None, prefix=''):
53 self.sort_methods = SortedDict(data=sort_methods)
56 default_sort = sort_methods[0][0]
58 self.default_sort = default_sort
64 self.has_pagesize = True
65 self.pagesizes = pagesizes
67 if not default_pagesize:
68 self.default_pagesize = pagesizes[int(math.ceil(float(len(pagesizes)) / 2)) - 1]
70 self.default_pagesize = default_pagesize
72 self.has_pagesize = False
74 self.force_sort = force_sort
77 def preferences(self, request):
78 if request.user.is_authenticated():
79 if request.user.prop.pagination:
80 preferences = request.user.prop.pagination.get(self.id, {})
84 preferences = request.session.get('paginator_%s%s' % (self.prefix, self.id), {})
88 def set_preferences(self, request, preferences):
89 if request.user.is_authenticated():
90 all_preferences = request.user.prop.pagination or {}
91 all_preferences[self.id] = preferences
92 request.user.prop.pagination = all_preferences
94 request.session['paginator_%s%s' % (self.prefix, self.id)] = preferences
96 def pagesize(self, request, session_prefs=None):
98 session_prefs = self.preferences(request)
101 if self.has_pagesize:
102 if request.GET.get(self.PAGESIZE, None):
104 pagesize = int(request.GET[self.PAGESIZE])
106 logging.error('Found invalid page size "%s", loading %s, refered by %s' % (
107 request.GET.get(self.PAGESIZE, ''), request.path, request.META.get('HTTP_REFERER', 'UNKNOWN')
111 session_prefs[self.PAGESIZE] = pagesize
113 pagesize = session_prefs.get(self.PAGESIZE, self.default_pagesize)
115 if not pagesize in self.pagesizes:
116 pagesize = self.default_pagesize
122 def page(self, request):
124 return int(request.GET.get(self.PAGE, "1").strip())
126 logging.error('Found invalid page number "%s", loading %s, refered by %s' % (
127 request.GET.get(self.PAGE, ''), request.path, request.META.get('HTTP_REFERER', 'UNKNOWN')
131 def sort(self, request, session_prefs=None):
132 if not session_prefs:
133 session_prefs = self.preferences(request)
136 sticky = request.user.is_authenticated() and request.user.prop.preferences and request.user.prop.preferences.get('sticky_sorts', False)
139 if request.GET.get(self.SORT, None):
140 sort = request.GET[self.SORT]
143 session_prefs[self.SORT] = sort
145 sort = self.force_sort or (sticky and session_prefs.get(self.SORT, None)) or self.default_sort
147 if not sort in self.sort_methods:
148 sort = self.default_sort
152 def sorted(self, objects, request, session_prefs=None):
153 sort = self.sort(request, session_prefs)
156 objects = self.sort_methods[sort].apply(objects)
162 return self.prefix and "%s_%s" % (self.prefix, _('pagesize')) or _('pagesize')
166 return self.prefix and "%s_%s" % (self.prefix, _('page')) or _('page')
170 return self.prefix and "%s_%s" % (self.prefix, _('sort')) or _('sort')
172 page_numbers_template = template.loader.get_template('paginator/page_numbers.html')
173 page_sizes_template = template.loader.get_template('paginator/page_sizes.html')
174 sort_tabs_template = template.loader.get_template('paginator/sort_tabs.html')
176 def paginated(request, paginators, tpl_context):
177 if len(paginators) == 2 and isinstance(paginators[0], basestring):
178 paginators = (paginators,)
180 for list_name, context in paginators:
181 tpl_context[list_name] = _paginated(request, tpl_context[list_name], context)
185 def _paginated(request, objects, context):
186 session_prefs = context.preferences(request)
188 pagesize = context.pagesize(request, session_prefs)
189 page = context.page(request)
190 sort, objects = context.sorted(objects, request, session_prefs)
192 paginator = Paginator(objects, pagesize)
195 page_obj = paginator.page(page)
197 logging.error('Found invalid page number "%s", loading %s, refered by %s' % (
198 request.GET.get(context.PAGE, ''), request.path, request.META.get('HTTP_REFERER', 'UNKNOWN')
202 if context.base_path:
203 base_path = context.base_path
205 base_path = request.path
206 get_params = generate_uri(request.GET, (context.PAGE, context.PAGESIZE, context.SORT))
209 base_path += "?" + get_params
211 url_joiner = "?" in base_path and "&" or "?"
215 object_list = page_obj.object_list
217 #if hasattr(object_list, 'lazy'):
218 # return object_list.lazy()
220 paginator.page = get_page()
222 total_pages = paginator.num_pages
226 total_pages = paginator.num_pages
228 has_previous = page > 1
229 has_next = page < total_pages
231 range_start = page - context.visible_page_range / 2
232 range_end = page + context.visible_page_range / 2
235 range_end = context.visible_page_range
238 if range_end > total_pages:
239 range_start = total_pages - context.visible_page_range + 1
240 range_end = total_pages
247 url_builder = lambda n: mark_safe("%s%s%s=%s&%s=%s" % (escape(base_path), url_joiner, context.SORT, sort, context.PAGE, n))
249 url_builder = lambda n: mark_safe("%s%s%s=%s" % (escape(base_path), url_joiner, context.PAGE, n))
251 if range_start > (context.outside_page_range + 1):
252 page_numbers.append([(n, url_builder(n)) for n in range(1, context.outside_page_range + 1)])
253 page_numbers.append(None)
254 elif range_start > 1:
255 page_numbers.append([(n, url_builder(n)) for n in range(1, range_start)])
257 page_numbers.append([(n, url_builder(n)) for n in range(range_start, range_end + 1)])
259 if range_end < (total_pages - context.outside_page_range):
260 page_numbers.append(None)
261 page_numbers.append([(n, url_builder(n)) for n in range(total_pages - context.outside_page_range + 1, total_pages + 1)])
262 elif range_end < total_pages:
263 page_numbers.append([(n, url_builder(n)) for n in range(range_end + 1, total_pages + 1)])
265 return page_numbers_template.render(template.Context({
266 'has_previous': has_previous,
267 'previous_url': has_previous and url_builder(page - 1) or None,
268 'has_next': has_next,
269 'next_url': has_next and url_builder(page + 1) or None,
271 'page_numbers': page_numbers
273 paginator.page_numbers = page_nums
275 paginator.page_numbers = ''
280 url_builder = lambda s: mark_safe("%s%s%s=%s&%s=%s" % (escape(base_path), url_joiner, context.SORT, sort, context.PAGESIZE, s))
282 url_builder = lambda s: mark_safe("%s%s%s=%s" % (escape(base_path), url_joiner, context.PAGESIZE, s))
284 sizes = [(s, url_builder(s)) for s in context.pagesizes]
286 return page_sizes_template.render(template.Context({
291 paginator.page_sizes = page_sizes
293 paginator.page_sizes = ''
297 url_builder = lambda s: mark_safe("%s%s%s=%s" % (escape(base_path), url_joiner, context.SORT, s))
298 sorts = [(n, s.label, url_builder(n), strip_tags(s.description)) for n, s in context.sort_methods.items()]
300 for name, label, url, descr in sorts:
301 paginator.__dict__['%s_sort_link' % name] = url
303 return sort_tabs_template.render(template.Context({
306 'sticky': session_prefs.get('sticky_sort', False)
308 paginator.sort_tabs = sort_tabs()
309 paginator.sort_description = mark_safe(context.sort_methods[sort].description)
310 paginator.current_sort = sort
312 paginator.sort_tabs = paginator.sort_description = ''
313 paginator.current_sort = ''
315 context.set_preferences(request, session_prefs)
316 objects.paginator = paginator