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.encoding import smart_unicode
9 from django.utils.http import urlquote
10 from django.utils.safestring import mark_safe
11 from django.utils.html import strip_tags, escape
12 from forum.utils.html import sanitize_html
15 def generate_uri(querydict, exclude=None):
18 for k, l in querydict.iterlists():
19 if (not exclude) or (not k in exclude):
20 all += ["%s=%s" % (k, escape(strip_tags(v))) for v in l]
24 class SortBase(object):
25 def __init__(self, label, description=''):
27 self.description = description
29 class SimpleSort(SortBase):
30 def __init__(self, label, order_by, description=''):
31 super(SimpleSort, self) .__init__(label, description)
32 self.order_by = order_by
34 def _get_order_by(self):
35 return isinstance(self.order_by, (list, tuple)) and self.order_by or [self.order_by]
37 def apply(self, objects):
39 return objects.order_by(*self._get_order_by())
43 class PaginatorContext(object):
44 visible_page_range = 5
45 outside_page_range = 1
49 def __init__(self, id, sort_methods=None, default_sort=None, force_sort = None,
50 pagesizes=None, default_pagesize=None, prefix=''):
54 self.sort_methods = SortedDict(data=sort_methods)
57 default_sort = sort_methods[0][0]
59 self.default_sort = default_sort
65 self.has_pagesize = True
66 self.pagesizes = pagesizes
68 if not default_pagesize:
69 self.default_pagesize = pagesizes[int(math.ceil(float(len(pagesizes)) / 2)) - 1]
71 self.default_pagesize = default_pagesize
73 self.has_pagesize = False
75 self.force_sort = force_sort
78 def preferences(self, request):
79 if request.user.is_authenticated():
80 if request.user.prop.pagination:
81 preferences = request.user.prop.pagination.get(self.id, {})
85 preferences = request.session.get('paginator_%s%s' % (self.prefix, self.id), {})
89 def set_preferences(self, request, preferences):
90 if request.user.is_authenticated():
91 all_preferences = request.user.prop.pagination or {}
92 all_preferences[self.id] = preferences
93 request.user.prop.pagination = all_preferences
95 request.session['paginator_%s%s' % (self.prefix, self.id)] = preferences
97 def pagesize(self, request, session_prefs=None):
99 session_prefs = self.preferences(request)
102 if self.has_pagesize:
103 if request.GET.get(self.PAGESIZE, None):
105 pagesize = int(request.GET[self.PAGESIZE])
107 logging.error('Found invalid page size "%s", loading %s, refered by %s' % (
108 request.GET.get(self.PAGESIZE, ''), request.path, request.META.get('HTTP_REFERER', 'UNKNOWN')
112 session_prefs[self.PAGESIZE] = pagesize
114 pagesize = session_prefs.get(self.PAGESIZE, self.default_pagesize)
116 if not pagesize in self.pagesizes:
117 pagesize = self.default_pagesize
123 def page(self, request):
125 return int(request.GET.get(self.PAGE, "1").strip())
127 logging.error('Found invalid page number "%s", loading %s, refered by %s' % (
128 request.GET.get(self.PAGE, ''), request.path, request.META.get('HTTP_REFERER', 'UNKNOWN')
132 def sort(self, request, session_prefs=None):
133 if not session_prefs:
134 session_prefs = self.preferences(request)
137 sticky = request.user.is_authenticated() and request.user.prop.preferences and request.user.prop.preferences.get('sticky_sorts', False)
140 if request.GET.get(self.SORT, None):
141 sort = request.GET[self.SORT]
144 session_prefs[self.SORT] = sort
146 sort = self.force_sort or (sticky and session_prefs.get(self.SORT, None)) or self.default_sort
148 if not sort in self.sort_methods:
149 sort = self.default_sort
153 def sorted(self, objects, request, session_prefs=None):
154 sort = self.sort(request, session_prefs)
157 objects = self.sort_methods[sort].apply(objects)
163 return self.prefix and "%s_%s" % (self.prefix, _('pagesize')) or _('pagesize')
167 return self.prefix and "%s_%s" % (self.prefix, _('page')) or _('page')
171 return self.prefix and "%s_%s" % (self.prefix, _('sort')) or _('sort')
173 page_numbers_template = template.loader.get_template('paginator/page_numbers.html')
174 page_sizes_template = template.loader.get_template('paginator/page_sizes.html')
175 sort_tabs_template = template.loader.get_template('paginator/sort_tabs.html')
177 def paginated(request, paginators, tpl_context):
178 if len(paginators) == 2 and isinstance(paginators[0], basestring):
179 paginators = (paginators,)
181 for list_name, context in paginators:
182 tpl_context[list_name] = _paginated(request, tpl_context[list_name], context)
186 def _paginated(request, objects, context):
187 session_prefs = context.preferences(request)
189 pagesize = context.pagesize(request, session_prefs)
190 page = context.page(request)
191 sort, objects = context.sorted(objects, request, session_prefs)
193 paginator = Paginator(objects, pagesize)
196 page_obj = paginator.page(page)
198 logging.error('Found invalid page number "%s", loading %s, refered by %s' % (
199 request.GET.get(context.PAGE, ''), request.path, request.META.get('HTTP_REFERER', 'UNKNOWN')
203 if context.base_path:
204 base_path = context.base_path
206 base_path = request.path
207 get_params = generate_uri(request.GET, (context.PAGE, context.PAGESIZE, context.SORT))
210 base_path += "?" + get_params
212 url_joiner = "?" in base_path and "&" or "?"
216 object_list = page_obj.object_list
218 #if hasattr(object_list, 'lazy'):
219 # return object_list.lazy()
221 paginator.page = get_page()
223 total_pages = paginator.num_pages
227 total_pages = paginator.num_pages
229 has_previous = page > 1
230 has_next = page < total_pages
232 range_start = page - context.visible_page_range / 2
233 range_end = page + context.visible_page_range / 2
236 range_end = context.visible_page_range
239 if range_end > total_pages:
240 range_start = total_pages - context.visible_page_range + 1
241 range_end = total_pages
248 url_builder = lambda n: mark_safe("%s%s%s=%s&%s=%s" % (escape(base_path), url_joiner, context.SORT, sort, context.PAGE, n))
250 url_builder = lambda n: mark_safe("%s%s%s=%s" % (escape(base_path), url_joiner, context.PAGE, n))
252 if range_start > (context.outside_page_range + 1):
253 page_numbers.append([(n, url_builder(n)) for n in range(1, context.outside_page_range + 1)])
254 page_numbers.append(None)
255 elif range_start > 1:
256 page_numbers.append([(n, url_builder(n)) for n in range(1, range_start)])
258 page_numbers.append([(n, url_builder(n)) for n in range(range_start, range_end + 1)])
260 if range_end < (total_pages - context.outside_page_range):
261 page_numbers.append(None)
262 page_numbers.append([(n, url_builder(n)) for n in range(total_pages - context.outside_page_range + 1, total_pages + 1)])
263 elif range_end < total_pages:
264 page_numbers.append([(n, url_builder(n)) for n in range(range_end + 1, total_pages + 1)])
266 return page_numbers_template.render(template.Context({
267 'has_previous': has_previous,
268 'previous_url': has_previous and url_builder(page - 1) or None,
269 'has_next': has_next,
270 'next_url': has_next and url_builder(page + 1) or None,
272 'page_numbers': page_numbers
274 paginator.page_numbers = page_nums
276 paginator.page_numbers = ''
281 url_builder = lambda s: mark_safe("%s%s%s=%s&%s=%s" % (escape(base_path), url_joiner, context.SORT, sort, context.PAGESIZE, s))
283 url_builder = lambda s: mark_safe("%s%s%s=%s" % (escape(base_path), url_joiner, context.PAGESIZE, s))
285 sizes = [(s, url_builder(s)) for s in context.pagesizes]
287 return page_sizes_template.render(template.Context({
292 paginator.page_sizes = page_sizes
294 paginator.page_sizes = ''
298 url_builder = lambda s: mark_safe("%s%s%s=%s" % (escape(base_path), url_joiner, context.SORT, s))
299 sorts = [(n, s.label, url_builder(n), strip_tags(s.description)) for n, s in context.sort_methods.items()]
301 for name, label, url, descr in sorts:
302 paginator.__dict__['%s_sort_link' % name] = smart_unicode(url)
304 return sort_tabs_template.render(template.Context({
307 'sticky': session_prefs.get('sticky_sort', False)
309 paginator.sort_tabs = sort_tabs()
310 paginator.sort_description = mark_safe(context.sort_methods[sort].description)
311 paginator.current_sort = sort
313 paginator.sort_tabs = paginator.sort_description = ''
314 paginator.current_sort = ''
316 context.set_preferences(request, session_prefs)
317 objects.paginator = paginator