CRM分页 ——第17天
1、分页的前端展示代码:
<nav> <ul class="pagination"> {% if query_sets.has_previous %} <li class=""><a href="?page={{ query_sets.previous_page_number }}">上页</a></li> {% endif %} {# <li class="active"><a>{{ query_sets.number }}</a></li>#} {% for loop_counter in query_sets.paginator.page_range %} {% render_page_ele loop_counter query_sets filter_condtions%} {% endfor %} {% if query_sets.has_next %} <li class=""><a href="?page={{ query_sets.next_page_number }}">下页</a></li> {% endif %} {# <li class="disabled"><a href="#">«</a></li>#} {# <li class="active"><a href="#">1 <span class="sr-only">(current)</span></a></li>#} {# #} </ul> </nav>
2、在view.py文件中返回给前端的字段代码:
#django的分页器 Paginator
from django.core.paginator import Paginator
paginator = Paginator(book_list, 2) #设置每一页显示几条 创建一个panginator对象
query_sets.paginator.page_range 这个相等于Paginator.page_range
query_sets = paginator.page(page=2) #展示页的数据对象
#query_sets.number表示当前页= paginator.page(page=2).number
print(Paginator.count) #总数据量 print(Paginator.num_pages) #总分页数 print(Paginator.page_range) #显示的是页数的标记 就是按钮的数目,表示页数的范围 print(page2.has_next()) #是否有下一页 print(page2.next_page_number()) #下一页的页码 print(page2.has_previous()) #是否有上一页 print(page2.previous_page_number()) #上一页的页码
def display_table_objs(request,app_name,table_name): print("-->",app_name,table_name) #models_module = importlib.import_module('%s.models'%(app_name)) #model_obj = getattr(models_module,table_name) admin_class = kind_admin.enabled_admins[app_name][table_name] #admin_class = king_admin.enabled_admins[crm][userprofile] #object_list = admin_class.model.objects.all() object_list,filter_condtions = table_filter(request,admin_class) paginator = Paginator(object_list, admin_class.list_per_page) # Show 25 contacts per page print("paginator------",paginator) page = request.GET.get('page') try: query_sets = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. query_sets = paginator.page(1) #这个是对分页的数据进行取值
except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. query_sets = paginator.page(paginator.num_pages) print("query_sets------------",query_sets) return render(request,"kindadmin/table_objs.html",{"admin_class":admin_class, "query_sets":query_sets, "filter_condtions":filter_condtions})
3、在自定标签定义一个函数返回分页值,因为当去筛选的时候也会把请求的page当成是查询条件,所以当有page字段时使用continue不往下执行把page也当作筛选条件
@register.simple_tag def render_page_ele(loop_counter,query_sets,filter_condtions): sel_ele ="" for k,v in filter_condtions.items(): sel_ele+="&%s=%s"%(k,v) if abs(query_sets.number - loop_counter) <= 1: ele_class = "" if query_sets.number == loop_counter: ele_class = "active" ele = '''<li class="%s"><a href="?page=%s%s">%s</a></li>''' %(ele_class,loop_counter,sel_ele,loop_counter) return mark_safe(ele) return ''