Ticket #19261: django_ticket_19261_django_core_paginator_page_getitem_2.patch

File django_ticket_19261_django_core_paginator_page_getitem_2.patch, 2.0 KB (added by trbs, 13 years ago)
  • django/core/paginator.py

    diff --git a/django/core/paginator.py b/django/core/paginator.py
    index 6c502ae..2909494 100644
    a b  
    11import collections
    22from math import ceil
    33
     4from django.utils import six
     5
    46class InvalidPage(Exception):
    57    pass
    68
    class Page(collections.Sequence):  
    9193    def __getitem__(self, index):
    9294        # The object_list is converted to a list so that if it was a QuerySet
    9395        # it won't be a database hit per __getitem__.
     96        if not isinstance(index, (slice,) + six.integer_types):
     97            raise TypeError
    9498        return list(self.object_list)[index]
    9599
    96100    def has_next(self):
  • tests/regressiontests/pagination/tests.py

    diff --git a/tests/regressiontests/pagination/tests.py b/tests/regressiontests/pagination/tests.py
    index a49f9b8..440c731 100644
    a b class ModelPaginationTests(TestCase):  
    266266        self.assertEqual(1, p.previous_page_number())
    267267        self.assertEqual(6, p.start_index())
    268268        self.assertEqual(9, p.end_index())
     269
     270    def test_page_getitem(self):
     271        """
     272        Tests that a paginator page raises the correct exception when slicing it.
     273        """
     274        paginator = Paginator(Article.objects.all(), 5)
     275        p = paginator.page(1)
     276
     277        # Make sure object_list queryset is not evaluated by an invalid __getitem__ call.
     278        # (this happens from the template engine when using eg: {% page_obj.has_previous %}
     279        self.assertEqual(p.object_list._result_cache, None)
     280        self.assertRaises(TypeError, lambda: p['has_previous'])
     281        self.assertEqual(p.object_list._result_cache, None)
     282
     283        # Make sure slicing the Page object with numbers and slice objects work.
     284        self.assertEqual(p[0], Article.objects.get(headline='Article 1'))
     285        self.assertEqual(p[slice(2)], [
     286            Article.objects.get(headline='Article 1'),
     287            Article.objects.get(headline='Article 2')
     288        ])
Back to Top