本文共 3481 字,大约阅读时间需要 11 分钟。
在我们平时浏览网页时,经常会遇到网页里条目很多的情形,这时就会用到分页展示的功能。那么,在Django中,是如何实现网页分类的功能的呢?答案是Paginator类。
本次分享讲具体展示如何利用Django的Paginator类来实现网页的分页展示功能。
首先我们要展示的内容是159首陶渊明的诗歌,它们储存在'/home/vagrant/poem.txt'文件中。
默认的不分页的网页(page.html)如下:
其模板的代码如下:
选择好条目数,在点击select按钮,可链接到如下页面:
这个页面(fenye.html)显示每页10条,可以点击按钮‘Return To Original Page’回到刚才的页面(page.html)。该页面(fenye.html)的模板代码如下:
from django.http import HttpResponsefrom django.shortcuts import render_to_responsefrom django.utils.datastructures import MultiValueDictKeyErrorfrom django.core.paginator import Paginator,PageNotAnInteger,EmptyPage#show items in default def output(request): # get items show on the page from poems.txt with open('/home/vagrant/poems.txt', 'r') as f: text = f.readlines() items_each_page = 15 # how many items in each page paginator = Paginator(text, items_each_page) page = request.GET.get('page') # get 'page' try: contacts = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. contacts = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. contacts = paginator.page(paginator.num_pages) return render_to_response('page.html',{'contacts': contacts})#show items by your choicedef output2(request): with open('/home/vagrant/poems.txt', 'r') as f: text = f.readlines() try: #try to get 'items', if None or failed, do nothing. a = request.GET.get('items') if str(a) != 'None': with open('/home/vagrant/num.txt', 'w') as f: f.write(a) except: pass with open('/home/vagrant/num.txt','r') as f: items_each_page = int(f.read()) paginator = Paginator(text, items_each_page) page = request.GET.get('page') try: contacts = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. contacts = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. contacts = paginator.page(paginator.num_pages) return render_to_response('fenye.html',{'contacts': contacts})这样,我们就基本实现了在Django中网页分页展示的功能,而且能够自己选择每一页需要展示的条目的数量,这显然是非常方便使用的。
本次分享到此结束,如有问题,欢迎大家交流与批评~~