#django #python #wagtail

Here's a simple recipe to add pagination to a Wagtail page:

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from wagtail.core.models import Page

class BlogIndexPage(Page):

    def get_context(self, request, *args, **kwargs):
        
        context = super(BlogIndexPage, self).get_context(request)

        all_posts = BlogIndexPage.objects.posts(self, request=request)
                max_items_per_page = 10
        paginator = Paginator(all_posts, max_items_per_page)

        page = request.GET.get('page')
        try:
            posts = paginator.page(page)
        except PageNotAnInteger:
            posts = paginator.page(1)
        except EmptyPage:
            posts = paginator.page(paginator.num_pages)

        context['posts'] = posts
        return context

In the template, you can have:

{% load wagtailcore_tags %}

{% if items.paginator.num_pages > 1 %}

    <nav id="post-nav">

        <span class="prev">
            {% if items.has_previous %}
                <a href="?page={{ items.previous_page_number }}">Newer posts</a>
            {% endif %}
        </span>

        {% for page_num in items.paginator.page_range %}
            {% if page_num == resources.number %}
                {{ page_num }}
            {% else %}
                <a href="?page={{ page_num }}">{{ page_num }}</a>
            {% endif %}
        {% endfor %}

        <span class="next">
            {% if items.has_next %}
                <a href="?page={{ items.next_page_number }}">Older posts</a>
            {% endif %}
        </span>

    </nav>

{% endif %}

This will give you the previous and next links and the full list of pages.