#django #python #wagtail

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

 1from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
 2
 3from wagtail.core.models import Page
 4
 5class BlogIndexPage(Page):
 6
 7    def get_context(self, request, *args, **kwargs):
 8        
 9        context = super(BlogIndexPage, self).get_context(request)
10
11        all_posts = BlogIndexPage.objects.posts(self, request=request)
12                max_items_per_page = 10
13        paginator = Paginator(all_posts, max_items_per_page)
14
15        page = request.GET.get('page')
16        try:
17            posts = paginator.page(page)
18        except PageNotAnInteger:
19            posts = paginator.page(1)
20        except EmptyPage:
21            posts = paginator.page(paginator.num_pages)
22
23        context['posts'] = posts
24        return context

In the template, you can have:

 1{% load wagtailcore_tags %}
 2
 3{% if items.paginator.num_pages > 1 %}
 4
 5    <nav id="post-nav">
 6
 7        <span class="prev">
 8            {% if items.has_previous %}
 9                <a href="?page={{ items.previous_page_number }}">Newer posts</a>
10            {% endif %}
11        </span>
12
13        {% for page_num in items.paginator.page_range %}
14            {% if page_num == resources.number %}
15                {{ page_num }}
16            {% else %}
17                <a href="?page={{ page_num }}">{{ page_num }}</a>
18            {% endif %}
19        {% endfor %}
20
21        <span class="next">
22            {% if items.has_next %}
23                <a href="?page={{ items.next_page_number }}">Older posts</a>
24            {% endif %}
25        </span>
26
27    </nav>
28
29{% endif %}

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