2024-05-19 01:59:43 -04:00
|
|
|
from typing import Callable
|
|
|
|
|
|
|
|
from django.core.paginator import Page, Paginator
|
2017-12-14 20:25:55 -05:00
|
|
|
from django.shortcuts import redirect
|
|
|
|
|
2018-07-02 19:51:51 -04:00
|
|
|
from lemoncurry.middleware import ResponseException
|
|
|
|
|
2017-12-14 20:25:55 -05:00
|
|
|
|
2024-05-19 01:59:43 -04:00
|
|
|
def paginate(queryset, reverse: Callable[[int], str], page: int | None) -> Page:
|
|
|
|
def redirect_to_page(i: int):
|
|
|
|
raise ResponseException(redirect(reverse(i)))
|
2017-12-14 20:25:55 -05:00
|
|
|
|
2024-05-19 01:59:43 -04:00
|
|
|
def reversible(p: Page) -> Page:
|
|
|
|
p.reverse = reverse
|
|
|
|
return p
|
2017-12-14 20:25:55 -05:00
|
|
|
|
2017-12-14 20:34:36 -05:00
|
|
|
paginator = Paginator(queryset, 10)
|
2017-12-14 20:25:55 -05:00
|
|
|
|
2024-05-19 01:59:43 -04:00
|
|
|
# If no page number was specified, return page one.
|
|
|
|
if page is None:
|
|
|
|
return reversible(paginator.page(1))
|
|
|
|
|
|
|
|
# If the first page was explicitly requested, or the page number was negative, redirect to page one with no URL suffix.
|
|
|
|
if page <= 1:
|
|
|
|
redirect_to_page(1)
|
2017-12-14 20:25:55 -05:00
|
|
|
|
2024-05-19 01:59:43 -04:00
|
|
|
# If the page requested is larger than the last page, then redirect to the last page.
|
|
|
|
if page > paginator.num_pages:
|
|
|
|
redirect_to_page(paginator.num_pages)
|
2017-12-14 20:25:55 -05:00
|
|
|
|
2024-05-19 01:59:43 -04:00
|
|
|
# Just return the current page! Hooray!
|
|
|
|
return reversible(paginator.page(page))
|