Python django.core.paginator.Page() Examples

The following are 30 code examples of django.core.paginator.Page(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.core.paginator , or try the search function .
Example #1
Source File: test_explorer_view.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setUp(self):
        # Find root page
        self.root_page = Page.objects.get(id=1)

        # Find page with an associated site
        self.site_page = Page.objects.get(id=2)

        # Add another top-level page (which will have no corresponding site record)
        self.no_site_page = SimplePage(
            title="Hello world!",
            slug="hello-world",
            content="hello",
        )
        self.root_page.add_child(instance=self.no_site_page)

    # Tests for users that have both add-site permission, and explore permission at the given view;
    # warning messages should include advice re configuring sites 
Example #2
Source File: pagination.py    From eoj3 with MIT License 6 votes vote down vote up
def paginate_queryset(self, queryset, page_size):
    """
    Paginate the queryset, if needed.
    """
    paginator = self.get_paginator(
      queryset, page_size, orphans=self.get_paginate_orphans(),
      allow_empty_first_page=self.get_allow_empty())
    page_kwarg = self.page_kwarg
    page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1
    try:
      page_number = int(page)
    except ValueError:
      raise Http404(_("Page can not be converted to an int."))
    try:
      page = paginator.page(page_number)
      return (paginator, page, page.object_list, page.has_other_pages())
    except InvalidPage as e:
      raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
        'page_number': page_number,
        'message': str(e)
      }) 
Example #3
Source File: tests_utils_paginator.py    From Spirit with MIT License 6 votes vote down vote up
def tests_paginate(self):
        # first page
        items = list(range(0, 20))
        page = paginate(items, per_page=10)
        self.assertIsInstance(page, Page)
        self.assertEqual(list(page), items[:10])

        # second page
        page = paginate(items, per_page=10, page_number=2)
        self.assertEqual(list(page), items[10:20])

        # invalid page
        self.assertRaises(Http404, paginate,
                          items, per_page=10, page_number=99)

        # empty first page
        page = paginate([], per_page=10)
        self.assertListEqual(list(page), []) 
Example #4
Source File: serializers.py    From esdc-ce with Apache License 2.0 6 votes vote down vote up
def data(self):
        """
        Returns the serialized data on the serializer.
        """
        if self._data is None:
            obj = self.object

            if self.many is not None:
                many = self.many
            else:
                many = hasattr(obj, '__iter__') and not isinstance(obj, (Page, dict))
                if many:
                    raise AssertionError('Implicit list/queryset serialization is deprecated. '
                                         'Use the `many=True` flag when instantiating the serializer.')

            if many:
                self._data = [self.to_native(item) for item in obj]
            else:
                self._data = self.to_native(obj)

        return self._data

    # noinspection PyMethodMayBeStatic 
Example #5
Source File: mixins.py    From djangorest-alchemy with MIT License 6 votes vote down vote up
def paginate_query_object(self, query_object, page_size):
        """Paginate the query object."""
        paginator = self.get_paginator(
            query_object, page_size,
            allow_empty_first_page=self.get_allow_empty())
        page = self.kwargs.get('page') or self.request.GET.get('page') or 1
        try:
            page_number = int(page)
        except ValueError:
            if page == 'last':
                page_number = paginator.num_pages
            else:
                raise InvalidPage("Page is not 'last', "
                                  "nor can it be converted to an int.")

        # DB2 fix for invalid 0 literal.
        # Generates FETCH 0 rows if not done this way
        if not paginator.count == 0:
            page = paginator.page(page_number)
            return (paginator, page, page.object_list, page.has_other_pages())
        else:
            return (paginator, Page([], 1, paginator), [], False) 
Example #6
Source File: paginator.py    From OMS with Apache License 2.0 5 votes vote down vote up
def page(self, number):
        """
        Returns a Page object for the given 1-based page number.
        """
        number = self.validate_number(number)
        # remove the extra item(s) when creating the page
        page_items = self.object_list[:self.per_page]
        return FinitePage(page_items, number, self) 
Example #7
Source File: test_explorer_view.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_admin_can_explore_every_page(self):
        self.assertTrue(self.client.login(username='superman', password='password'))
        for page in Page.objects.all():
            response = self.client.get(reverse('wagtailadmin_explore', args=[page.pk]))
            self.assertEqual(response.status_code, 200) 
Example #8
Source File: test_explorer_view.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_nonadmin_sees_breadcrumbs_up_to_cca(self):
        self.assertTrue(self.client.login(username='josh', password='password'))
        response = self.client.get(reverse('wagtailadmin_explore', args=[6]))
        self.assertEqual(response.status_code, 200)
        # While at "Page 1", Josh should see the breadcrumbs leading only as far back as the example.com homepage,
        # since it's his Closest Common Ancestor.
        self.assertInHTML(
            """<li class="home"><a href="/admin/pages/4/" class="icon icon-home text-replace">Home</a></li>""",
            str(response.content)
        )
        self.assertInHTML("""<li><a href="/admin/pages/5/">Content</a></li>""", str(response.content))
        # The page title shouldn't appear because it's the "home" breadcrumb.
        self.assertNotContains(response, "Welcome to example.com!") 
Example #9
Source File: paginator.py    From Spirit with MIT License 5 votes vote down vote up
def render_paginator(context, page, page_var='page', hashtag=''):
    query_dict = context["request"].GET.copy()

    try:
        del query_dict[page_var]
    except KeyError:
        pass

    extra_query = ""

    if query_dict:
        extra_query = "&%s" % query_dict.urlencode()

    if hashtag:
        hashtag = "#%s" % hashtag

    new_context = {
        "page": page,
        "page_var": page_var,
        "hashtag": hashtag,
        "extra_query": extra_query
    }

    if isinstance(page, Page):
        template = "spirit/utils/paginator/_paginator.html"
    else:
        template = "spirit/utils/paginator/_yt_paginator.html"

    return render_to_string(template, new_context) 
Example #10
Source File: paginator.py    From OMS with Apache License 2.0 5 votes vote down vote up
def page(self, number):
        """
        Returns a Page object for the given 1-based page number.
        """
        number = self.validate_number(number)
        bottom = (number - 1) * self.per_page
        top = bottom + self.per_page
        page_items = self.object_list[bottom:top]
        # check moved from validate_number
        if not page_items:
            if number == 1 and self.allow_empty_first_page:
                pass
            else:
                raise EmptyPage('That page contains no results')
        return InfinitePage(page_items, number, self) 
Example #11
Source File: paginator.py    From OMS with Apache License 2.0 5 votes vote down vote up
def __repr__(self):
        return '<Page %s>' % self.number 
Example #12
Source File: bookmarks.py    From linkding with MIT License 5 votes vote down vote up
def bookmark_list(context, bookmarks: Page):
    return {
        'bookmarks': bookmarks,
    } 
Example #13
Source File: restframework2.py    From django-elasticsearch with MIT License 5 votes vote down vote up
def data(self):
        if self._data is None:
            if type(self.object) is Page:
                page = self.object
                self._data = {
                    'count': page.paginator.count,
                    'previous': self.fields['previous'].to_native(page),
                    'next': self.fields['next'].to_native(page),
                    'results': page.object_list
                }

        return super(ElasticsearchPaginationSerializer, self).data 
Example #14
Source File: pagination.py    From eoj3 with MIT License 5 votes vote down vote up
def page(self, number):
    """
    Returns a Page object for the given 1-based page number.
    """
    number = self.validate_number(number)
    bottom = (number - 1) * self.per_page
    top = bottom + self.per_page
    return self._get_page(self.object_list[bottom:top], number, self) 
Example #15
Source File: pagination.py    From eoj3 with MIT License 5 votes vote down vote up
def _get_page(self, *args, **kwargs):
    """
    Returns an instance of a single page.

    This hook can be used by subclasses to use an alternative to the
    standard :cls:`Page` object.
    """
    return EndlessPage(*args, **kwargs) 
Example #16
Source File: pagination.py    From eoj3 with MIT License 5 votes vote down vote up
def __repr__(self):
    return '<Page %s of Endless Page>' % self.number 
Example #17
Source File: paginator.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def page(self, number):
        """
        Returns a Page object for the given 1-based page number.
        """
        number = self.validate_number(number)
        bottom = (number - 1) * self.per_page
        top = bottom + self.per_page
        page_items = self.object_list[bottom:top]
        # check moved from validate_number
        if not page_items:
            if number == 1 and self.allow_empty_first_page:
                pass
            else:
                raise EmptyPage('That page contains no results')
        return InfinitePage(page_items, number, self) 
Example #18
Source File: test_explorer_view.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_explore_with_missing_page_model(self):
        # Create a ContentType that doesn't correspond to a real model
        missing_page_content_type = ContentType.objects.create(app_label='tests', model='missingpage')
        # Turn /home/old-page/ into this content type
        Page.objects.filter(id=self.old_page.id).update(content_type=missing_page_content_type)

        # try to browse the the listing that contains the missing model
        response = self.client.get(reverse('wagtailadmin_explore', args=(self.root_page.id, )))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'wagtailadmin/pages/index.html')

        # try to browse into the page itself
        response = self.client.get(reverse('wagtailadmin_explore', args=(self.old_page.id, )))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'wagtailadmin/pages/index.html') 
Example #19
Source File: test_explorer_view.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_pages(self):
        for i in range(150):
            self.root_page.add_child(instance=SimplePage(
                title="Page " + str(i),
                slug="page-" + str(i),
                content="hello",
            )) 
Example #20
Source File: test_explorer_view.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_reordering(self):
        response = self.client.get(
            reverse('wagtailadmin_explore', args=(self.root_page.id, )),
            {'ordering': 'ord'}
        )
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'wagtailadmin/pages/index.html')
        self.assertEqual(response.context['ordering'], 'ord')

        # child pages should be ordered by native tree order (i.e. by creation time)
        page_ids = [page.id for page in response.context['pages']]
        self.assertEqual(page_ids, [self.child_page.id, self.old_page.id, self.new_page.id])

        # Pages must not be paginated
        self.assertNotIsInstance(response.context['pages'], paginator.Page) 
Example #21
Source File: test_explorer_view.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_explore_root(self):
        response = self.client.get(reverse('wagtailadmin_explore_root'))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'wagtailadmin/pages/index.html')
        self.assertEqual(Page.objects.get(id=1), response.context['parent_page'])
        self.assertTrue(response.context['pages'].paginator.object_list.filter(id=self.root_page.id).exists()) 
Example #22
Source File: test_explorer_view.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        # Find root page
        self.root_page = Page.objects.get(id=2)

        # Add child page
        self.child_page = SimplePage(
            title="Hello world!",
            slug="hello-world",
            content="hello",
        )
        self.root_page.add_child(instance=self.child_page)

        # more child pages to test ordering
        self.old_page = StandardIndex(
            title="Old page",
            slug="old-page",
            latest_revision_created_at=local_datetime(2010, 1, 1)
        )
        self.root_page.add_child(instance=self.old_page)

        self.new_page = SimplePage(
            title="New page",
            slug="new-page",
            content="hello",
            latest_revision_created_at=local_datetime(2016, 1, 1)
        )
        self.root_page.add_child(instance=self.new_page)

        # Login
        self.user = self.login() 
Example #23
Source File: Serializer.py    From django-angularjs-blog with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _data_convert(data, time_func, foreign, many, include_attr, exclude_attr):
    if isinstance(data, models.Model):
        attr_list = _get_attr(data, time_func, foreign, many)
        _include_check(include_attr, attr_list)
        _exclude_check(exclude_attr, attr_list)
        return attr_list
    elif isinstance(data, (QuerySet, Page)):
        result = []
        for itm in data:
            attr_list = _get_attr(itm, time_func, foreign, many)
            _include_check(include_attr, attr_list)
            _exclude_check(exclude_attr, attr_list)
            result.append(copy.copy(attr_list))
        return result
    elif isinstance(data, datetime.datetime):
        print '===='
        print data
        return time_func(data)
    elif isinstance(data, (unicode, str, bool, float)):
        return data
    elif isinstance(data, dict):
        for k, v in data.iteritems():
            data[k] = _data_convert(v, time_func, foreign, many, include_attr, exclude_attr)
        return data
    elif isinstance(data, list):
        for i, itm in enumerate(data):
            data[i] = _data_convert(itm, time_func, foreign, many, include_attr, exclude_attr)
        return data
    else:
        return None 
Example #24
Source File: paginator.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def page(self, number):
        """
        Returns a Page object for the given 1-based page number.
        """
        number = self.validate_number(number)
        # remove the extra item(s) when creating the page
        page_items = self.object_list[:self.per_page]
        return FinitePage(page_items, number, self) 
Example #25
Source File: paginator.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __repr__(self):
        return '<Page %s>' % self.number 
Example #26
Source File: paginator.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def page(self, number):
        """
        Returns a Page object for the given 1-based page number.
        """
        number = self.validate_number(number)
        bottom = (number - 1) * self.per_page
        top = bottom + self.per_page
        page_items = self.object_list[bottom:top]
        # check moved from validate_number
        if not page_items:
            if number == 1 and self.allow_empty_first_page:
                pass
            else:
                raise EmptyPage('That page contains no results')
        return InfinitePage(page_items, number, self) 
Example #27
Source File: paginator.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __repr__(self):
        return '<Page %s>' % self.number 
Example #28
Source File: paginator.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def page(self, number):
        """
        Returns a Page object for the given 1-based page number.
        """
        number = self.validate_number(number)
        bottom = (number - 1) * self.per_page
        top = bottom + self.per_page
        page_items = self.object_list[bottom:top]
        # check moved from validate_number
        if not page_items:
            if number == 1 and self.allow_empty_first_page:
                pass
            else:
                raise EmptyPage('That page contains no results')
        return InfinitePage(page_items, number, self) 
Example #29
Source File: paginator.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def page(self, number):
        """
        Returns a Page object for the given 1-based page number.
        """
        number = self.validate_number(number)
        # remove the extra item(s) when creating the page
        page_items = self.object_list[:self.per_page]
        return FinitePage(page_items, number, self) 
Example #30
Source File: paginator.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __repr__(self):
        return '<Page %s>' % self.number