Skip to content

Updated new pagination feature. #523

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
File renamed without changes.
6 changes: 6 additions & 0 deletions base/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
class IncorectLookupParameter(Exception):
"""
Raised when a query parameter contains an incorrect value.
"""

pass
Empty file added base/migrations/__init__.py
Empty file.
58 changes: 58 additions & 0 deletions base/pagination.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
from django.core.paginator import InvalidPage, Paginator

from .exceptions import IncorectLookupParameter

PAGE_VAR = "page"


class Pagination:
def __init__(
self,
request,
model,
queryset,
list_per_page,
):
self.model = model
self.opts = model._meta
self.queryset = queryset
self.list_per_page = list_per_page
try:
# Get the current page from the query string.
self.page_num = int(request.GET.get(PAGE_VAR, 1))
except ValueError:
self.page_num = 1
self.params = dict(request.GET.lists())
self.setup()

@property
def page_range(self):
"""
Returns the full range of pages.
"""
return (
self.paginator.get_elided_page_range(self.page_num)
if self.multi_page
else []
)

def setup(self):
paginator = Paginator(self.queryset, self.list_per_page)
result_count = paginator.count
# Determine use pagination.
multi_page = result_count > self.list_per_page

self.result_count = result_count
self.multi_page = multi_page
self.paginator = paginator
self.page = paginator.get_page(self.page_num)

def get_objects(self):
if not self.multi_page:
result_list = self.queryset._clone()
else:
try:
result_list = self.paginator.page(self.page_num).object_list
except InvalidPage:
raise IncorectLookupParameter
return result_list
Empty file added base/templatetags/__init__.py
Empty file.
69 changes: 69 additions & 0 deletions base/templatetags/base_templatetags.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
from collections.abc import Iterable, Mapping

from django import template
from django.http import QueryDict
from django.template.exceptions import TemplateSyntaxError

register = template.Library()


# This template tag is scheduled to be added in Django 6.0.
# Imported for use before the release of Django 6.0.
@register.simple_tag(name="querystring", takes_context=True)
def querystring(context, *args, **kwargs):
"""
Build a query string using `args` and `kwargs` arguments.

This tag constructs a new query string by adding, removing, or modifying
parameters from the given positional and keyword arguments. Positional
arguments must be mappings (such as `QueryDict` or `dict`), and
`request.GET` is used as the starting point if `args` is empty.

Keyword arguments are treated as an extra, final mapping. These mappings
are processed sequentially, with later arguments taking precedence.

A query string prefixed with `?` is returned.

Raise TemplateSyntaxError if a positional argument is not a mapping or if
keys are not strings.

For example::

{# Set a parameter on top of `request.GET` #}
{% querystring foo=3 %}

{# Remove a key from `request.GET` #}
{% querystring foo=None %}

{# Use with pagination #}
{% querystring page=page_obj.next_page_number %}

{# Use a custom ``QueryDict`` #}
{% querystring my_query_dict foo=3 %}

{# Use multiple positional and keyword arguments #}
{% querystring my_query_dict my_dict foo=3 bar=None %}
"""
if not args:
args = [context.request.GET]
params = QueryDict(mutable=True)
for d in [*args, kwargs]:
if not isinstance(d, Mapping):
raise TemplateSyntaxError(
"querystring requires mappings for positional arguments (got "
"%r instead)." % d
)
for key, value in d.items():
if not isinstance(key, str):
raise TemplateSyntaxError(
"querystring requires strings for mapping keys (got %r "
"instead)." % key
)
if value is None:
params.pop(key, None)
elif isinstance(value, Iterable) and not isinstance(value, str):
params.setlist(key, value)
else:
params[key] = value
query_string = params.urlencode() if params else ""
return f"?{query_string}"
40 changes: 40 additions & 0 deletions base/templatetags/components.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from django import template
from django.utils.html import format_html
from django.utils.safestring import mark_safe

from base.pagination import PAGE_VAR

from .base_templatetags import querystring

register = template.Library()


@register.simple_tag
def pagination_number(pagination, i):
"""
Generate an individual page index link in a paginated list.
"""
if i == pagination.paginator.ELLIPSIS:
return format_html("{} ", pagination.paginator.ELLIPSIS)
elif i == pagination.page_num:
return format_html('<em class="current-page" aria-current="page">{}</em> ', i)
else:
link = querystring(None, pagination.params, {PAGE_VAR: i})
return format_html(
'<a href="{}" aria-label="page {}" {}>{}</a> ',
link,
i,
mark_safe(' class="end"' if i == pagination.paginator.num_pages else ""),
i,
)


@register.inclusion_tag("base/components/pagination.html", name="pagination")
def pagination_tag(pagination):
previous_page_link = f"?{PAGE_VAR}={pagination.page_num - 1}"
next_page_link = f"?{PAGE_VAR}={pagination.page_num + 1}"
return {
"pagination": pagination,
"previous_page_link": previous_page_link,
"next_page_link": next_page_link,
}
Empty file added base/tests/__init__.py
Empty file.
21 changes: 21 additions & 0 deletions base/tests/migrations/0002_fish.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Generated by Django 3.2.15 on 2025-06-04 05:19

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('tests', '0001_initial'),
]

operations = [
migrations.CreateModel(
name='Fish',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('price', models.IntegerField()),
],
),
]
Empty file.
7 changes: 6 additions & 1 deletion ratings/tests/models.py → base/tests/models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
from django.db import models

from ..models import RatedItemBase, Ratings
from ratings.models import RatedItemBase, Ratings


class Fish(models.Model):
name = models.CharField(max_length=255)
price = models.IntegerField()


class Food(models.Model):
Expand Down
60 changes: 60 additions & 0 deletions base/tests/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
from django.test import RequestFactory, TestCase

from base.pagination import Pagination

from .models import Fish


class PaginationTestCase(TestCase):
@classmethod
def setUpTestData(cls):
fishs = [Fish(name=f"fish-{i}", price=i * 100) for i in range(1, 101)]
Fish.objects.bulk_create(fishs)
cls.queryset = Fish.objects.all()
cls.factory = RequestFactory()

def test_pagination_attributes(self):
request = self.factory.get("/fake-url/")
pagination = Pagination(request, Fish, self.queryset, 5)
self.assertEqual(pagination.result_count, 100)
self.assertTrue(pagination.multi_page)
pagination = Pagination(request, Fish, self.queryset, 200)
self.assertFalse(pagination.multi_page)

def test_pagination_page_range(self):
request = self.factory.get("/fake-url/")
ELLIPSIS = "…"
case = [
(2, 6, [1, 2, 3, 4, 5, 6, 7, 8, 9, ELLIPSIS, 49, 50]),
(3, 10, [1, 2, ELLIPSIS, 7, 8, 9, 10, 11, 12, 13, ELLIPSIS, 33, 34]),
(4, 23, [1, 2, ELLIPSIS, 20, 21, 22, 23, 24, 25]),
(5, 20, [1, 2, ELLIPSIS, 17, 18, 19, 20]),
(10, 8, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]),
(20, 1, [1, 2, 3, 4, 5]),
]
for list_per_page, current_page, expected_page_range in case:
with self.subTest(list_per_page=list_per_page, current_page=current_page):
pagination = Pagination(request, Fish, self.queryset, list_per_page)
pagination.page_num = current_page
self.assertEqual(list(pagination.page_range), expected_page_range)

def test_pagination_result_objects(self):
request = self.factory.get("/fake-url/")
case = [
(2, 25, ["49", "50"]),
(4, 12, ["45", "46", "47", "48"]),
(5, 10, ["46", "47", "48", "49", "50"]),
(7, 11, ["71", "72", "73", "74", "75", "76", "77"]),
(10, 10, ["91", "92", "93", "94", "95", "96", "97", "98", "99", "100"]),
(200, 1, [str(i) for i in range(1, 101)]),
]
Fish.objects.all().delete()
fishs = [Fish(name=i, price=i * 100) for i in range(1, 101)]
Fish.objects.bulk_create(fishs)
queryset = Fish.objects.all().order_by("id")
for list_per_page, current_page, expect_object_names in case:
pagination = Pagination(request, Fish, queryset, list_per_page)
pagination.page_num = current_page
objects = pagination.get_objects()
object_names = list(objects.values_list("name", flat=True))
self.assertEqual(object_names, expect_object_names)
Loading