Pagination effect:
View code:
1 # -*- coding: utf-8 -*- 2 from django.shortcuts import render,get_object_or_404 3 from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage 4 5 from .models import Article 6 7 # Create your views here. 8 9 def index(request): 10 # latest_article_list = Article.objects.order_by(‘update‘)[:5] 11 # cOntext= {‘latest_article_list‘: latest_article_list} 12 # return render(request, ‘blog/index.html‘,context) 13 article_list = Article.objects.all().order_by(‘cre_date‘) 14 paginator = Paginator(article_list,2) #show 2 articles per page 15 16 page = request.GET.get(‘page‘) 17 18 try: 19 articles = paginator.page(page) 20 except PageNotAnInteger: 21 #The page number is not an integer, return to the first page. 22 articles = paginator.page(1) 23 except EmptyPage: 24 articles = paginator.page(paginator.num_pages) 25 26 return render(request, 'blog/index.html', { 'articles': articles})
paginator is a paging instance, page is the page number parameter passed by the link to the backend, and articles is an instance of each page.
In this example, the paginator divides all articles (article_list) into three pages according to two sections per page. page is the page number requested by the front end. Articles are the specific articles (2 articles) within the page number returned based on the requested page number.
For details on the properties and methods of paginator and articles, please see the documentation: https://docs.djangoproject.com/en/1.8/topics/pagination/
Front-end code:
1 2 <nav> 3 <div class="pagination pagination-right"> 4 <ul > 5 <li> 6 {% if articles.has_previous %} 7 <a href="?page={{ articles.previous_page_number } }" class="active">«</ a> 8 {% endif %} 9 {% if not articles.has_previous %} 10 <a href="" > «a> 11 {% endif %} 12 </li> 13 14 <li> 15 {% for i in articles.paginator.page_range %} 16 <li {% if articles.number == i %}class="active"{% endif %}> 17 <a href="?page={{ i }}" >{{ i }} 18 19 </a> 20 </li> 21 {% endfor %} 22 </li> 23 24 <li> 25 {% if articles.has_next %} 26 <a href="?page={{ articles.next_page_number } }" >»</a> 27 {% endif %} 28 {% if not articles.has_next %} 29 <a href="" > »</a> 30 {% endif %} 31 </li> 32 33 <li> 34 Total {{ articles.paginator.num_pages }} pages 35 </li> 36 </ul> 37 </div> 38 </nav> 39
Django implements paging function