Created
March 24, 2012 15:20
-
-
Save diox/2184204 to your computer and use it in GitHub Desktop.
clamp_pagination() for django-pagination app
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@register.simple_tag(takes_context=True) | |
def clamp_pagination(context, key): | |
""" | |
Force number of pages to be never be more than PAGINATION_FIXED_NB_PAGES | |
""" | |
paginator = context.get('paginator') | |
page_obj = context.get('page_obj') | |
if paginator and page_obj: | |
max_num_pages = getattr(settings, 'PAGINATION_FIXED_NB_PAGES', 10) | |
if hasattr(paginator, '_num_pages') and hasattr(paginator, '_count'): | |
# If it's a "real" paginator with count, num pages etc, clamp it to our max value | |
paginator._num_pages = min(paginator.num_pages, max_num_pages) | |
max_count = paginator.num_pages * paginator.per_page | |
paginator._count = min(paginator.count, max_count) | |
if hasattr(page_obj, 'cached_has_next') and page_obj.number == max_num_pages: | |
# If the paginator has a cache for the next page, force it to False it we | |
# are on the last page | |
page_obj.cached_has_next = False | |
if page_obj.number > max_num_pages: | |
# Raising Http404 is sadly useless : it doesn't work inside templatetags, | |
# it's too late. Instead, we emulate what {% autopaginate %} does | |
del context['paginator'] | |
del context['page_obj'] | |
context[key] = [] | |
context['invalid_page'] = True | |
return u'' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment