python測試開發django-117.bootstrapTable結合Paginator分頁器查顯示表格


前言

bootstrap 提供了table表格插件,可以快速幫我們實現分頁功能。這樣就不用在前端頁面上寫分頁邏輯,只需關注后端給對應數據就行。
bootstrap-table提供兩種分頁方式,client和server,即客戶端和服務端分頁;

  • client分頁:后台一次性返回所有數據,前台翻頁時不再請求后台(數據量很大的時候會導致查詢很慢)。
  • server分頁:后台根據前台每次翻頁時傳遞的參數,可以結合Paginator分頁器查詢每個頁碼對應的數據,每次只返回對應頁面的數據

bootstrap-table

下載所需要的包

Bootstrap 中文網:http://www.bootcss.com/
Bootstrap Table 官網:https://bootstrap-table.com/
JQuery 官網:https://jquery.com/

放置static文件中,目錄結構如下

模板中頭部引用

# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/

<head>
 {% load static %}
 <title>bootstrap-table</title>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <meta name="description" content="" />
 <meta name="keywords" content="" />
 <link rel="stylesheet" type="text/css" href="/static/bootstarp/css/bootstrap.min.css" >
 <link rel="stylesheet" type="text/css" href="/static/bootstrap-table/dist/bootstrap-table.min.css" >

 <script type="text/javascript" src="/static/bootstarp/jquery/jquery-3.6.0.min.js"></script>
 <script type="text/javascript" src="/static/bootstarp/js/bootstrap.min.js"></script>
 <script type="text/javascript" src="/static/bootstrap-table/dist/bootstrap-table.min.js"></script>
 <script type="text/javascript" src="/static/bootstrap-table/dist/locale/bootstrap-table-zh-CN.min.js"></script>

</head>

bootstrapTable實現數據加載

script 中bootstrapTable 幾個摘要參數
url: 訪問數據的接口,需返回json對象,如:{"total": 2,"rows": [{"id": 0,"name": "Item 0","price": "$0"},]
columns: table表格中顯示的字段和名稱
queryParams:查詢的時候,提交查詢參數

<body>
<div class="container">
    <h1>bootstrapTable實例</h1>
    <hr/>

    <div id="toolbar" class="btn-group">
        <button id="btn_add" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
        </button>
        <button id="btn_edit" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
        </button>
        <button id="btn_delete" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>刪除
        </button>
    </div>

    <table id="table" class="table table-striped"></table>
</div>
</body>
<script>
    var url = '/teacher/info';
    var columns = [
        {
            checkbox: true,
            visible: true                  //是否顯示復選框
        },
        {
            field: 'id',
            title: 'ID'
        }, {
            field: 'name',
            title: '姓名'
        }, {
            field: 'age',
            title: '年齡'
        },
         {
            field: 'tel',
            title: '電話'
        }
    ];
    $("#table").bootstrapTable({
        toolbar: '#toolbar',                //自定義工具按鈕
        url: url,                           //請求后台的URL(*)
        method: 'get',                      //請求方式(*)
        cache: false,                       //是否使用緩存,默認為true,所以一般情況下需要設置一下這個屬性(*)
        pagination: true,                   //是否顯示分頁(*)
        pageSize: 10,                       //每頁的記錄行數(*)
        pageList: [10, 20, 50, 100, 'All'], //可供選擇的每頁的行數(*)
        sidePagination: "server",           //分頁方式:client客戶端分頁,server服務端分頁(*)
        pageNumber: 1,                      //初始化加載第一頁,默認第一頁
        //search: true,                       //是否顯示表格搜索
        showColumns: true,                  //是否顯示所有的列
        showRefresh: true,                  //是否顯示刷新按鈕
        minimumCountColumns: 2,             //最少允許的列數
        //height: 500,                      //行高,如果沒有設置height屬性,表格自動根據記錄條數決定表格高度
        showToggle: true,                   //是否顯示詳細視圖和列表視圖的切換按鈕
        columns: columns,                   //列參數
        //detailView: true,                  //是否顯示父子表
        //得到查詢的參數,會在url后面拼接,如:?rows=5&page=2&sortOrder=asc&search_kw=&_=1564105760651
        queryParams: function (params) {
            //這里的鍵的名字和控制器的變量名必須一直,這邊改動,控制器也需要改成一樣的
            var query_params = {
                page: (params.offset / params.limit) + 1,   //頁碼
                size: params.limit,    //頁面大小
                //查詢框中的參數傳遞給后台
                //search_kw: $('#search-keyword').val(), // 請求時向服務端傳遞的參數
            };
            return query_params;
        },

    });
    //得到查詢的參數


</script>
</html>

視圖

查詢結果必須是json格式:{"total": 2,"rows": [{},{}]},其中total和rows名稱必須保持一致,前端才能加載到數據

from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Q
from django.forms.models import model_to_dict
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/


def teacherpage(request):
    return render(request, 'boot_table.html')

def teacherInfo(request):
    """
    查詢結果必須是json格式:{"total": 2,"rows": [{},{}]}
    """
    if request.method == "GET":
        # search_kw = request.GET.get('search_kw', None)
        # 獲取分頁參數用於查詢對應頁面數據,page為第幾頁,size為每頁數據條數
        page_num = request.GET.get('page',  1)
        size = request.GET.get('size', 10)
        # 查詢全部
        teachers = Teacher.objects.all()
        # 使用分頁器返回查詢的頁數和size
        paginator = Paginator(teachers, per_page=size)
        page_object = paginator.page(page_num)

        # 總數
        total = teachers.count()
        # 查詢list of dict
        rows = [model_to_dict(i) for i in page_object]
        # print(rows)
        return JsonResponse({'total': total, 'rows': rows})

頁面展示效果

默認每頁查詢10條數據

可以修改每頁顯示的條數

queryParams 查詢

queryParams查詢對應的參數

  • params.limit 是每頁的條數,一般對應size參數
  • params.offset 是起始位置的數目,對應的page需要計算得到(params.offset / params.limit) + 1
  • search_kw 對應搜索框內容,需設置.bootstrapTable屬性 search: true

toolbar 工具

toolbar 對應table表格上的新增/修改/刪除

<div id="toolbar" class="btn-group">
        <button id="btn_add" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
        </button>
        <button id="btn_edit" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
        </button>
        <button id="btn_delete" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>刪除
        </button>
    </div>

此部分后端接口還沒實現

參考教程:https://www.cnblogs.com/landeanfen/p/4976838.html
bootstrap-table官方文檔:https://examples.bootstrap-table.com/
bootstrap-table API在線查看效果:https://live.bootstrap-table.com/
bootstrap table 方法 詳細教程: https://www.itxst.com/bootstrap-table-methods/tutorial.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM