django 后端分页
阅读原文时间:2023年07月08日阅读:3

分页处理脚本:

# -*- coding: utf-8 -*-

@Time : 2019-01-22 10:41

@Author : 小贰

@FileName: page.py

@function: 作者比较懒什么都没写

def control(current_page,page_nums):

list\_size = 5  
if page\_nums<=list\_size:  
    page\_list= list(range(1,page\_nums+1))  
else:  
    if (page\_nums-list\_size)<=list\_size:  
        page\_list = list(range(1,page\_nums+1))  
    else:  
        if (page\_nums-current\_page)<list\_size:  
            page\_list = \[1,2,"..."\]+list(range(page\_nums - 4, page\_nums + 1))  
        else:  
            if current\_page>list\_size:  
                page\_list = list(range(current\_page-4, current\_page + 1)) + \["...", page\_nums - 1, page\_nums\]  
            else:  
                page\_list = list(range(1, list\_size + 1)) + \["...", page\_nums - 1, page\_nums\]  
return page\_list

if __name__ == "__main__":
current_page=120
page_nums=200
print(control(current_page,page_nums))

视图:

class OpsLog(View):
"""操作日志"""
@method_decorator(csrf_exempt)
@method_decorator(login_check)
@method_decorator(perms_check)
def dispatch(self, request, *args, **kwargs):
return super(OpsLog,self).dispatch(request,*args, **kwargs)

def get(self,request,page=1):  
    title = "操作日志"  
    audit\_obj = log\_db.OpsLog.objects.all().order\_by("-start\_time")  
    pagesize = 13  
    paginator = Paginator(audit\_obj, pagesize)  
    # 从前端获取当前的页码数,默认为1  
    # 把当前的页码数转换成整数类型  
    currentPage = int(page)  
    page\_nums = paginator.num\_pages  
    #获取分页信息  
    page\_list = pg.control(currentPage, page\_nums)  
    try:  
        audit\_list = paginator.page(page)  # 获取当前页码的记录  
    except PageNotAnInteger:  
        audit\_list = paginator.page(1)  # 如果用户输入的页码不是整数时,显示第1页的内容  
    except EmptyPage:  
        audit\_list = paginator.page(paginator.num\_pages)

    return render(request,'log\_opslog.html',locals())

url配置:

urlpatterns = [
path("opslog//",views.OpsLog.as_view()),
]

模板:

    {#上一页按钮开始#} {# 如果当前页有上一页#} {% if audit\_list.has\_previous %} {# 当前页的上一页按钮正常使用#} {% else %} {# 当前页的不存在上一页时,上一页的按钮不可用#} {% endif %} {#上一页按钮结束#} {# 页码开始#} {% for num in page\_list %} {% if num == currentPage %}
  • {{ num }}
  • {% else %}
  • {{ num }}
  • {% endif %} {% endfor %} {#页码结束#} {# 下一页按钮开始#} {% if audit\_list.has\_next %} {% else %} {% endif %} {# 下一页按钮结束#}

效果: