1.导入分页相关模块
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
2.将对象分页,如下是按每页3条记录分页
customer_list = models.Customer.objects.all()
paginator = Paginator(customer_list,3)
翻到第1页:paginator.page(1)
翻到最后一页:paginator.page(paginator.num_pages)
当前页:customer_list.number
所有页内循环:for page_num in customer_list.paginator.page_range
3.前端控制
前端显示左翻页“<",页面数字,右翻页">"
1 <nav> 2 <ul class="pagination"> 3 {% if customer_list.has_previous %} 4 <li class=""> 5 <a href="?page={{ customer_list.previous_page_number }}" aria-label="Previous"> 6 <span aria-hidden="true">«</span> 7 </a> 8 </li> 9 {% endif %} 10 {% for page_num in customer_list.paginator.page_range %} 11 {% guess_page customer_list.number page_num %} 12 {% endfor %} 13 {% if customer_list.has_next %} 14 <li class=""><a href="?page={{ customer_list.next_page_number }}" aria-label="Next"><span aria-hidden="true">»</span></a></li> 15 {% endif %} 16 </ul> 17 </nav>
自定义的函数,用于显示页面数字,当是当前时调用样式显示,否则无样式,如下:
def guess_page(current_page,loop_num): offset = abs(current_page - loop_num) if offset <3: if current_page == loop_num: page_ele = ‘‘‘<li class="active"><a href="?page=%s">%s</a></li>‘‘‘ %(loop_num,loop_num) else: page_ele = ‘‘‘<li class=""><a href="?page=%s">%s</a></li>‘‘‘ %(loop_num,loop_num) return format_html(page_ele) else: return ‘‘
时间: 2024-10-10 08:58:38