X-Git-Url: http://git.ithinksw.org/philo.git/blobdiff_plain/ee24ab2feac614a0bdc7114e8e2b4b4d0ad44395..aa974af0f752e8b3e23337764e0bbd5e140217d8:/contrib/penfield/utils.py?ds=inline diff --git a/contrib/penfield/utils.py b/contrib/penfield/utils.py index 5df800c..0318e5e 100644 --- a/contrib/penfield/utils.py +++ b/contrib/penfield/utils.py @@ -1,20 +1,33 @@ -from django.core.paginator import Paginator, InvalidPage, EmptyPage +from django.core.paginator import Paginator -def paginate(request, entries, entries_per_page): - paginator = Paginator(entries, entries_per_page) +def paginate(objects, per_page=None, page_number=1): + """ + Given a list of objects, return a (page, obj_list) tuple. + """ try: - page_number = int(request.GET.get('page', '1')) - entries = paginator.page(page_number).object_list - page = paginator.page(page_number) - except ValueError: - page_number = 1 - entries = paginator.page(page_number).object_list - page = paginator.page(page_number) + per_page = int(per_page) + except (TypeError, ValueError): + # Then either it wasn't set or it was set to an invalid value + return None, objects + + # There also shouldn't be pagination if the list is too short. Try count() + # first - good chance it's a queryset, where count is more efficient. + try: + if objects.count() <= per_page: + return None, objects + except AttributeError: + if len(objects) <= per_page: + return None, objects + + paginator = Paginator(objects, per_page) try: - entries = paginator.page(page_number).object_list - page = paginator.page(page_number) - except (EmptyPage, InvalidPage): - entries = paginator.page(paginator.num_pages).object_list - page = paginator.page(page_number) - return page \ No newline at end of file + page_number = int(page_number) + except: + page_number = 1 + + # This will raise an EmptyPage error if the page number is out of range. + # This error is intentionally left for the calling function to handle. + page = paginator.page(page_number) + + return page, page.object_list \ No newline at end of file