diff --git a/django/core/paginator.py b/django/core/paginator.py index 7887ffa638..439b0bc717 100644 --- a/django/core/paginator.py +++ b/django/core/paginator.py @@ -1,6 +1,12 @@ class InvalidPage(Exception): pass +class PageNotAnInteger(InvalidPage): + pass + +class EmptyPage(InvalidPage): + pass + class Paginator(object): def __init__(self, object_list, per_page, orphans=0, allow_empty_first_page=True): self.object_list = object_list @@ -14,14 +20,14 @@ class Paginator(object): try: number = int(number) except ValueError: - raise InvalidPage('That page number is not an integer') + raise PageNotAnInteger('That page number is not an integer') if number < 1: - raise InvalidPage('That page number is less than 1') + raise EmptyPage('That page number is less than 1') if number > self.num_pages: if number == 1 and self.allow_empty_first_page: pass else: - raise InvalidPage('That page contains no results') + raise EmptyPage('That page contains no results') return number def page(self, number): @@ -129,14 +135,14 @@ class ObjectPaginator(Paginator): try: page_number = int(page_number) + 1 except ValueError: - raise InvalidPage + raise PageNotAnInteger return self.validate_number(page_number) def get_page(self, page_number): try: page_number = int(page_number) + 1 except ValueError: - raise InvalidPage + raise PageNotAnInteger return self.page(page_number).object_list def has_next_page(self, page_number): diff --git a/docs/pagination.txt b/docs/pagination.txt index 20c6ca84cc..bfdf8eea1c 100644 --- a/docs/pagination.txt +++ b/docs/pagination.txt @@ -82,6 +82,21 @@ Attributes ``page_range`` -- A 1-based range of page numbers, e.g., ``[1, 2, 3, 4]``. +``InvalidPage`` exceptions +========================== + +The ``page()`` method raises ``InvalidPage`` if the requested page is invalid +(i.e., not an integer) or contains no objects. Generally, it's enough to trap +the ``InvalidPage`` exception, but if you'd like more granularity, you can trap +either of the following exceptions: + +``PageNotAnInteger`` -- Raised when ``page()`` is given a value that isn't an integer. + +``EmptyPage`` -- Raised when ``page()`` is given a valid value but no objects exist on that page. + +Both of the exceptions are subclasses of ``InvalidPage``, so you can handle +them both with a simple ``except InvalidPage``. + ``Page`` objects ================