#导入模块
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
#获取使用paginator函数分页集中sql_result,每25条为一页
#sql_result 是元组数据
paginator = Paginator(sql_result, 25)
#获取分页的数量
page_sum = paginator.num_pages
after_range_num = 3
before_range_num = 9
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
try:
#建立一个触点,包含sql_result的结果,传入html,使用for语句遍历出最终结果(contacts.object_list 代替原始的sql_result)
contacts = paginator.page(page)
except PageNotAnInteger:
contacts = paginator.page(1)
except EmptyPage:
contacts = paginator.page(paginator.num_pages)
#页面显示数据
if page >= after_range_num:
page_range = paginator.page_range[page-after_range_num:page+before_range_num]
else:
page_range = paginator.page_range[0:int(page)+before_range_num]
return render_to_response('index.html', {'contacts':contacts, 'page_sum':page_sum})
#下面是html内容
#展现数据的方式
<table border='1' cellpadding='3' cellspacing='0' align='center'>
{% for row in contacts.object_list %} #使用contacts.object_list 替代sql_result
<tr>
{% for v in row %} <td>`v`</td>
{% endfor %}
</tr>
{% endfor%}
</table><br>
#分页栏
<span>
{% if contacts.has_previous %}
<a href="?page=1">首页</a> <a href="?page=`contacts`.`previous_page_number`">上一页</a>
{% endif %}
{% for p in page_range %}
{% ifequal p contacts.number %}
<span>`p`</span>
{% else %}
<a href="?page=`p`">`p`</a>
{% endifequal %}
{% endfor %}
{% if contacts.has_next %} #尾页转到最后页,也就是统计页数的个数
<a href="?page=`contacts`.`next_page_number`">下一页</a> <a href="?page=`page_sum`">尾页</a>
{% endif%}
</span><br><br>
转载于:https://blog.51cto.com/wowoo1121/1740736