Adding pagination

When you start adding content to your blog, you will soon realize you need to split the list of posts across several pages. Django has a built-in pagination class that allows you to manage paginated data easily.

Edit the views.py file of the blog application to import the Django paginator classes and modify the post_list view, as follows:

from django.core.paginator import Paginator, EmptyPage,\                                  PageNotAnInteger def post_list(request):    object_list = Post.published.all()    paginator = Paginator(object_list, 3) # 3 posts in each page    page = request.GET.get('page')    try:        posts = paginator.page(page)    except PageNotAnInteger:        # If page is not an integer deliver the first page        posts = paginator.page(1)    except EmptyPage: # If page ...

Get Django 2 by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.