Pagination in Wagtail

前端 未结 3 760
挽巷
挽巷 2021-02-13 04:01

I\'m fairly new to Wagtail, and I am in the process of creating a site that will have a Resources (blog) section and I\'m not sure how to implement pagination so that there are

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-13 04:10

    Django provides the module django.core.paginator for this purpose: https://docs.djangoproject.com/en/1.10/topics/pagination/ . Using this within Wagtail is very similar to the examples in the Django documentation - the only real difference is that when you're setting up the Paginator object to be passed to the template, you do that with a get_context method on the page model, instead of a view function. Your model definition will look something like this:

    from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
    
    class ResourceIndexPage(Page):
        # ...
        def get_context(self, request):
            context = super(ResourceIndexPage, self).get_context(request)
    
            # Get the full unpaginated listing of resource pages as a queryset -
            # replace this with your own query as appropriate
            all_resources = ResourcePage.objects.live()
    
            paginator = Paginator(all_resources, 5) # Show 5 resources per page
    
            page = request.GET.get('page')
            try:
                resources = paginator.page(page)
            except PageNotAnInteger:
                # If page is not an integer, deliver first page.
                resources = paginator.page(1)
            except EmptyPage:
                # If page is out of range (e.g. 9999), deliver last page of results.
                resources = paginator.page(paginator.num_pages)
    
            # make the variable 'resources' available on the template
            context['resources'] = resources
    
            return context
    

    Within your template, you can now loop over the items using {% for resource in resources %}, and display the pagination links as follows:

      {% if resources.has_previous %}
    • {% endif %} {% for page_num in resources.paginator.page_range %}
    • {{ page_num }}
    • {% endfor %} {% if resources.has_next %}
    • {% endif %}

提交回复
热议问题