diff options
Diffstat (limited to 'lib/pagination')
-rw-r--r-- | lib/pagination/__init__.py | 1 | ||||
-rw-r--r-- | lib/pagination/middleware.py | 25 | ||||
-rw-r--r-- | lib/pagination/models.py | 1 | ||||
-rw-r--r-- | lib/pagination/templates/pagination/pagination.html | 30 | ||||
-rw-r--r-- | lib/pagination/templatetags/__init__.py | 1 | ||||
-rw-r--r-- | lib/pagination/templatetags/pagination_tags.py | 235 | ||||
-rw-r--r-- | lib/pagination/tests.py | 52 |
7 files changed, 345 insertions, 0 deletions
diff --git a/lib/pagination/__init__.py b/lib/pagination/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/lib/pagination/__init__.py @@ -0,0 +1 @@ + diff --git a/lib/pagination/middleware.py b/lib/pagination/middleware.py new file mode 100644 index 0000000..cf9f9cb --- /dev/null +++ b/lib/pagination/middleware.py @@ -0,0 +1,25 @@ +class PaginationMiddleware(object): + """ + Inserts a variable representing the current page onto the request object if + it exists in either **GET** or **POST** portions of the request. + """ + def process_request(self, request): + try: + request.page = int(request.REQUEST['page']) + except (KeyError, ValueError): + request.page = 1 + + def process_view(self, request, view_func, view_args, view_kwargs): + if 'paginate' in view_kwargs: + del view_kwargs['paginate'] + + if 'page_url' in view_kwargs: + request.page_url = view_kwargs['page_url'] + del view_kwargs['page_url'] + + if 'page' in view_kwargs: + request.page = int(view_kwargs['page']) + del view_kwargs['page'] + else: + request.page = 1 + diff --git a/lib/pagination/models.py b/lib/pagination/models.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/lib/pagination/models.py @@ -0,0 +1 @@ + diff --git a/lib/pagination/templates/pagination/pagination.html b/lib/pagination/templates/pagination/pagination.html new file mode 100644 index 0000000..2ecffb4 --- /dev/null +++ b/lib/pagination/templates/pagination/pagination.html @@ -0,0 +1,30 @@ +{% load pagination_tags %} +{% if is_paginated %} +<div class="pagination"> + {% if page_obj.has_previous %} + <a href="{% if use_page_path %}{% page_path prev_page %}{% else %}?page={{ page_obj.previous_page_number }}{{ getvars }}{% endif %}" class="prev">‹‹ previous</a> + {% else %} + <span class="disabled prev"></span> + {% endif %} + {% for page in pages %} + {% if page %} + {% ifequal page page_obj.number %} + <span class="current page">{{ page }}</span> + {% else %} + {% if use_page_path %} + <a href="{% page_path page %}" class="page">{{ page }}</a> + {% else %} + <a href="?page={{ page }}{{ getvars }}" class="page">{{ page }}</a> + {% endif %} + {% endifequal %} + {% else %} + ... + {% endif %} + {% endfor %} + {% if page_obj.has_next %} + <a href="{% if use_page_path %}{% page_path next_page %}{% else %}?page={{ page_obj.next_page_number }}{{ getvars }}{% endif %}" class="next">next ››</a> + {% else %} + <span class="disabled next">next ››</span> + {% endif %} +</div> +{% endif %} diff --git a/lib/pagination/templatetags/__init__.py b/lib/pagination/templatetags/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/lib/pagination/templatetags/__init__.py @@ -0,0 +1 @@ + diff --git a/lib/pagination/templatetags/pagination_tags.py b/lib/pagination/templatetags/pagination_tags.py new file mode 100644 index 0000000..ef9bf5e --- /dev/null +++ b/lib/pagination/templatetags/pagination_tags.py @@ -0,0 +1,235 @@ +try: + set +except NameError: + from sets import Set as set +import re +from django import template +from django.db.models.query import QuerySet +from django.core.paginator import Paginator, QuerySetPaginator, InvalidPage + +register = template.Library() + +DEFAULT_PAGINATION = 20 +DEFAULT_WINDOW = 4 +DEFAULT_ORPHANS = 0 + +@register.tag +def page_path(parser, token): + """Returns the path for the given page.""" + bits = token.split_contents() + if len(bits) != 2: + raise template.TemplateSyntaxError( + 'page_path requires a page template var' + ) + + return PagePathNode(bits[1]) + +class PagePathNode(template.Node): + """Renders the path for a given page number""" + def __init__(self, page_var): + self.page_var = page_var + + def render(self, context): + try: + page = int(context[self.page_var]) + path = context['request'].path + page_url = context['request'].page_url + except: + return '' + + return page_url % page + +def do_autopaginate(parser, token): + """ + Splits the arguments to the autopaginate tag and formats them correctly. + """ + split = token.split_contents() + if len(split) == 2: + return AutoPaginateNode(split[1]) + elif len(split) == 3: + try: + paginate_by = int(split[2]) + except ValueError: + raise template.TemplateSyntaxError(u'Got %s, but expected integer.' % split[2]) + return AutoPaginateNode(split[1], paginate_by=paginate_by) + elif len(split) == 4: + try: + paginate_by = int(split[2]) + except ValueError: + raise template.TemplateSyntaxError(u'Got %s, but expected integer.' % split[2]) + try: + orphans = int(split[3]) + except ValueError: + raise template.TemplateSyntaxError(u'Got %s, but expected integer.' % split[3]) + return AutoPaginateNode(split[1], paginate_by=paginate_by, orphans=orphans) + else: + raise template.TemplateSyntaxError('%r tag takes one required argument and one optional argument' % split[0]) + +class AutoPaginateNode(template.Node): + """ + Emits the required objects to allow for Digg-style pagination. + + First, it looks in the current context for the variable specified. This + should be either a QuerySet or a list. + + 1. If it is a QuerySet, this ``AutoPaginateNode`` will emit a + ``QuerySetPaginator`` and the current page object into the context names + ``paginator`` and ``page_obj``, respectively. + + 2. If it is a list, this ``AutoPaginateNode`` will emit a simple + ``Paginator`` and the current page object into the context names + ``paginator`` and ``page_obj``, respectively. + + It will then replace the variable specified with only the objects for the + current page. + + .. note:: + + It is recommended to use *{% paginate %}* after using the autopaginate + tag. If you choose not to use *{% paginate %}*, make sure to display the + list of availabale pages, or else the application may seem to be buggy. + """ + def __init__(self, queryset_var, paginate_by=DEFAULT_PAGINATION, orphans=DEFAULT_ORPHANS): + self.queryset_var = template.Variable(queryset_var) + self.paginate_by = paginate_by + self.orphans = orphans + + def render(self, context): + key = self.queryset_var.var + value = self.queryset_var.resolve(context) + if issubclass(value.__class__, QuerySet): + model = value.model + paginator_class = QuerySetPaginator + else: + value = list(value) + try: + model = value[0].__class__ + except IndexError: + return u'' + paginator_class = Paginator + paginator = paginator_class(value, self.paginate_by, self.orphans) + try: + page_obj = paginator.page(context['request'].page) + except InvalidPage: + context[key] = [] + context['invalid_page'] = True + return u'' + context[key] = page_obj.object_list + context['paginator'] = paginator + context['page_obj'] = page_obj + if hasattr(context['request'], 'page_url'): + context['use_page_path'] = True + return u'' + +def paginate(context, window=DEFAULT_WINDOW): + """ + Renders the ``pagination/pagination.html`` template, resulting in a + Digg-like display of the available pages, given the current page. If there + are too many pages to be displayed before and after the current page, then + elipses will be used to indicate the undisplayed gap between page numbers. + + Requires one argument, ``context``, which should be a dictionary-like data + structure and must contain the following keys: + + ``paginator`` + A ``Paginator`` or ``QuerySetPaginator`` object. + + ``page_obj`` + This should be the result of calling the page method on the + aforementioned ``Paginator`` or ``QuerySetPaginator`` object, given + the current page. + + This same ``context`` dictionary-like data structure may also include: + + ``getvars`` + A dictionary of all of the **GET** parameters in the current request. + This is useful to maintain certain types of state, even when requesting + a different page. + """ + try: + paginator = context['paginator'] + page_obj = context['page_obj'] + page_range = paginator.page_range + # First and last are simply the first *n* pages and the last *n* pages, + # where *n* is the current window size. + first = set(page_range[:window]) + last = set(page_range[-window:]) + # Now we look around our current page, making sure that we don't wrap + # around. + current_start = page_obj.number-1-window + if current_start < 0: + current_start = 0 + current_end = page_obj.number-1+window + if current_end < 0: + current_end = 0 + current = set(page_range[current_start:current_end]) + pages = [] + # If there's no overlap between the first set of pages and the current + # set of pages, then there's a possible need for elusion. + if len(first.intersection(current)) == 0: + first_list = sorted(list(first)) + second_list = sorted(list(current)) + pages.extend(first_list) + diff = second_list[0] - first_list[-1] + # If there is a gap of two, between the last page of the first + # set and the first page of the current set, then we're missing a + # page. + if diff == 2: + pages.append(second_list[0] - 1) + # If the difference is just one, then there's nothing to be done, + # as the pages need no elusion and are correct. + elif diff == 1: + pass + # Otherwise, there's a bigger gap which needs to be signaled for + # elusion, by pushing a None value to the page list. + else: + pages.append(None) + pages.extend(second_list) + else: + pages.extend(sorted(list(first.union(current)))) + # If there's no overlap between the current set of pages and the last + # set of pages, then there's a possible need for elusion. + if len(current.intersection(last)) == 0: + second_list = sorted(list(last)) + diff = second_list[0] - pages[-1] + # If there is a gap of two, between the last page of the current + # set and the first page of the last set, then we're missing a + # page. + if diff == 2: + pages.append(second_list[0] - 1) + # If the difference is just one, then there's nothing to be done, + # as the pages need no elusion and are correct. + elif diff == 1: + pass + # Otherwise, there's a bigger gap which needs to be signaled for + # elusion, by pushing a None value to the page list. + else: + pages.append(None) + pages.extend(second_list) + else: + pages.extend(sorted(list(last.difference(current)))) + to_return = { + 'pages': pages, + 'page_obj': page_obj, + 'paginator': paginator, + 'is_paginated': paginator.count > paginator.per_page, + } + if 'request' in context: + if 'use_page_path' in context: + to_return['request'] = context['request'] + to_return['use_page_path'] = context['use_page_path'] + to_return['prev_page'] = page_obj.previous_page_number() + to_return['next_page'] = page_obj.next_page_number() + + getvars = context['request'].GET.copy() + if 'page' in getvars: + del getvars['page'] + if len(getvars.keys()) > 0: + to_return['getvars'] = "&%s" % getvars.urlencode() + else: + to_return['getvars'] = '' + return to_return + except KeyError: + return {} +register.inclusion_tag('pagination/pagination.html', takes_context=True)(paginate) +register.tag('autopaginate', do_autopaginate) diff --git a/lib/pagination/tests.py b/lib/pagination/tests.py new file mode 100644 index 0000000..837e55c --- /dev/null +++ b/lib/pagination/tests.py @@ -0,0 +1,52 @@ +""" +>>> from django.core.paginator import Paginator +>>> from pagination.templatetags.pagination_tags import paginate +>>> from django.template import Template, Context + +>>> p = Paginator(range(15), 2) +>>> paginate({'paginator': p, 'page_obj': p.page(1)})['pages'] +[1, 2, 3, 4, 5, 6, 7, 8] + +>>> p = Paginator(range(17), 2) +>>> paginate({'paginator': p, 'page_obj': p.page(1)})['pages'] +[1, 2, 3, 4, 5, 6, 7, 8, 9] + +>>> p = Paginator(range(19), 2) +>>> paginate({'paginator': p, 'page_obj': p.page(1)})['pages'] +[1, 2, 3, 4, None, 7, 8, 9, 10] + +>>> p = Paginator(range(21), 2) +>>> paginate({'paginator': p, 'page_obj': p.page(1)})['pages'] +[1, 2, 3, 4, None, 8, 9, 10, 11] + +# Testing orphans +>>> p = Paginator(range(5), 2, 1) +>>> paginate({'paginator': p, 'page_obj': p.page(1)})['pages'] +[1, 2] + +>>> p = Paginator(range(21), 2, 1) +>>> paginate({'paginator': p, 'page_obj': p.page(1)})['pages'] +[1, 2, 3, 4, None, 7, 8, 9, 10] + +>>> t = Template("{% load pagination_tags %}{% autopaginate var 2 %}{% paginate %}") + +# WARNING: Please, please nobody read this portion of the code! +>>> class GetProxy(object): +... def __iter__(self): yield self.__dict__.__iter__ +... def copy(self): return self +... def urlencode(self): return u'' +... def keys(self): return [] +>>> class RequestProxy(object): +... page = 1 +... GET = GetProxy() +>>> +# ENDWARNING + +>>> t.render(Context({'var': range(21), 'request': RequestProxy()})) +u'\\n<div class="pagination">... +>>> +>>> t = Template("{% load pagination_tags %}{% autopaginate var %}{% paginate %}") +>>> t.render(Context({'var': range(21), 'request': RequestProxy()})) +u'\\n<div class="pagination">... +>>> +"""
\ No newline at end of file |