views.py
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def index(request): content_list = Post.objects.all() page = request.GET.get('page', 1) paginator = Paginator(content_list, 8) try: contents = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. contents = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. contents = paginator.page(paginator.num_pages) return render(request, "index.html", {'content_list':content_list, 'contents':contents})
templates
{% if contents.has_other_pages %} <ul class="pagination"> {% if contents.has_previous %} <li><a href="?page={{ contents.previous_page_number }}">«</a></li> {% else %} <li class="disabled"><span>«</span></li> {% endif %} {% for i in contents.paginator.page_range %} {% if contents.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if contents.has_next %} <li><a href="?page={{ contents.next_page_number }}">»</a></li> {% else %} <li class="disabled"><span>»</span></li> {% endif %} </ul> {% endif %}