django+bootstrp分页
自定义分页算法:
1 from django.core.paginator import Paginator 2 3 4 def page_fun(table_data_obj, page, page_split, around_count=2): 5 ''' 6 table_data_obj: 数据库査询的对象 7 page:获取某页的数据 8 around_count:当前页前后各显示多少页码,默认为2 9 page_split:每页显示多少数据 10 ''' 11 paginator = Paginator(table_data_obj, page_split) 12 page_obj = paginator.get_page(page) 13 current_page = page_obj.number # 获取当前页 14 num_pages = paginator.num_pages # 总的页数 15 left_has_more = False 16 right_has_more = False 17 if current_page <= around_count + 2: 18 left_pages = range(1, current_page) 19 else: 20 left_has_more = True 21 left_pages = range(current_page - around_count, current_page) 22 if current_page >= num_pages - around_count - 1: 23 right_pages = range(current_page + 1, num_pages + 1) 24 else: 25 right_has_more = True 26 right_pages = range(current_page + 1, current_page + around_count + 1) # 左闭右开区间 27 return { 28 'left_pages': left_pages, 29 'right_pages': right_pages, 30 'current_page': current_page, 31 'left_has_more': left_has_more, 32 'right_has_more': right_has_more, 33 'num_pages': num_pages, 34 'page_obj': page_obj, 35 }
views.py中使用上面定义的函数:
1 def p_test(request): 2 user = request.user.username 3 table_data_obj = Collocation_info.objects.filter( 4 responsible=user, is_active=True).all() 5 page = request.GET.get('p', 1) 6 page_data = page_fun(table_data_obj=table_data_obj, page=page, around_count=3, page_split=2) 7 return render(request, 'collocation_app/collocation_view.html', locals())
前端显示:
请自行引入bootstrap文件和jQuery文件
{% block body %} <ul> {% for data in page_data.page_obj %} <li>{{ data.id }}</li> {% endfor %} </ul> <ul class="pagination"> {# 显示上一页 #} {% if page_data.page_obj.has_previous %} <li><a href="{% url 'collocation_view' %}?p={{ page_obj.previous_page_number }}">上一页</a></li> {% else %} <li class="disabled"><a href="javascript:void(0);">上一页</a></li> {% endif %} {# 显示左边页码 #} {% if page_data.left_has_more %} <li><a href="{% url 'collocation_view' %}?p=1">1</a></li> <li><a href="javascript:void(0);">...</a></li> {% endif %} {% for left_page in page_data.left_pages %} <li><a href="{% url 'collocation_view' %}?p={{ left_page }}">{{ left_page }}</a></li> {% endfor %} {# 显示当前页 #} <li class="active"><a href="{% url 'collocation_view' %}?p={{ page_data.current_page }}">{{ page_data.current_page }}</a></li> {# 显示右边页码 #} {% for right_page in page_data.right_pages %} <li><a href="{% url 'collocation_view' %}?p={{ right_page }}">{{ right_page }}</a></li> {% endfor %} {% if page_data.right_has_more %} <li><a href="javascript:void(0);">...</a></li> <li><a href="{% url 'collocation_view' %}?p={{ page_data.num_pages }}">{{ page_data.num_pages }}</a></li> {% endif %} {# 显示下一页 #} {% if page_data.page_obj.has_next %} <li><a href="{% url 'collocation_view' %}?p={{ page_data.page_obj.next_page_number }}">下一页</a></li> {% else %} <li class="disabled"><a href="javascript:void(0);">下一页</a></li> {% endif %} </ul> {% endblock %}
最终显示第3页数据时的结果: