主頁 > 知識庫 > Django Paginator分頁器的使用示例

Django Paginator分頁器的使用示例

熱門標(biāo)簽:高德地圖標(biāo)注是免費(fèi)的嗎 老人電話機(jī)器人 地圖標(biāo)注視頻廣告 北京電信外呼系統(tǒng)靠譜嗎 洪澤縣地圖標(biāo)注 大連crm外呼系統(tǒng) 無錫客服外呼系統(tǒng)一般多少錢 梅州外呼業(yè)務(wù)系統(tǒng) 百度地圖標(biāo)注位置怎么修改
# name: models.py
from django.db import models

class User(models.Model):
    id = models.AutoField(primary_key=True)
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)

# 插入測試數(shù)據(jù)
import random
def index(request):
    for i in range(1,100):
        chars = []
        pasd = []
        for x in range(1,8):
            chars.append(random.choice('abcdefghijklmnopqrstuvwxyz'))
            pasd.append(random.choice('0987654321'))
        user = "".join(chars)
        pwd = "".join(pasd)
        models.User.objects.create(username=user, password=pwd)
    return HttpResponse("ok")
!--name: page.html-->
!DOCTYPE html>
html lang="en">
head>
    meta charset="UTF-8">
    title>Title/title>
     link rel="stylesheet"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >
/head>
body>
table class="table table-sm table-hover">
    thead>
        tr class="table-success">
            th> 序號/th> th> 用戶名/th> th> 用戶密碼/th>
        /tr>
    /thead>
    tbody>
        {% for article in user_list %}
            tr class="table-primary">
                td>{{ article.id }}/td>
                td>{{ article.username }}/td>
                td>{{ article.password }}/td>
            /tr>
        {% endfor %}
    /tbody>
/table>
nav class="d-flex justify-content-center" aria-label="Page navigation example">
    ul class="pagination">
        li class="page-item">a class="page-link" href="./page?id=1" rel="external nofollow"  rel="external nofollow" >首頁/a>/li>
        {% if user_list.has_previous %}
            li class="page-item">a class="page-link" href="./page?id={{ user_list.previous_page_number }}" rel="external nofollow"  rel="external nofollow" >上一頁/a>/li>
        {% else %}
            li class="page-item disabled">a class="page-link" href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >上一頁/a>/li>
        {% endif %}

        {% for item in paginator.page_range %}
            {% if item == currentPage %}
                li class="page-item active">a class="page-link" href="./page?id={{ item }}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >{{ item }}/a>/li>
            {% else %}
                li class="page-item">a class="page-link" href="./page?id={{ item }}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >{{ item }}/a>/li>
            {% endif %}
        {% endfor %}

        {% if user_list.has_next %}
            li class="page-item">a class="page-link" href="./page?id={{ user_list.next_page_number }}" rel="external nofollow"  rel="external nofollow" >下一頁/a>/li>
        {% else %}
            li class="page-item disabled">a class="page-link" href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >下一頁/a>/li>
        {% endif %}
        li class="page-item">a class="page-link" href="./page?id={{ paginator.num_pages }}" rel="external nofollow"  rel="external nofollow" >尾頁/a>/li>
    /ul>
/nav>

div style="text-align: center;" class="alert alert-dark">
   統(tǒng)計: {{ currentPage }}/{{ paginator.num_pages }} 共查詢到:{{ paginator.count }} 條數(shù)據(jù) 頁碼列表:{{ paginator.page_range }}
/div>
/body>
/html>
# name: views.py
from django.shortcuts import render,HttpResponse
from MyWeb import models
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

def page(request):
    user = models.User.objects.all()
    paginator = Paginator(user, 10)
    currentPage = int(request.GET.get("id",1))
    try:
        user_list = paginator.page(currentPage)
    except PageNotAnInteger:
        user_list = paginator.page(1)
    except:
        user_list = paginator.page(paginator.num_pages)

    return render(request,"page.html",{"user_list":user_list,
                                       "paginator":paginator,
                                       "currentPage":currentPage})
# name: urls.py
from MyWeb import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('page',views.page)
]

上方的分頁代碼還有一個不足之處,當(dāng)我們的頁碼數(shù)量過多時,會全部展示出來,整個頁面都是很不美觀,我們直接在上方代碼上稍加修改一下試試.

# name: views.py
from django.shortcuts import render,HttpResponse
from MyWeb import models
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

def page(request):
    user = models.User.objects.all()
    paginator = Paginator(user, 10)
    currentPage = int(request.GET.get("id",1))

    if paginator.num_pages > 15:
        if currentPage-5  1:
            pageRange = range(1,11)
        elif currentPage+5 > paginator.num_pages:
            pageRange = range(currentPage-5,paginator.num_pages)
        else:
            pageRange = range(currentPage-5,currentPage+5)
    else:
        pageRange = paginator.page_range

    try:
        user_list = paginator.page(currentPage)
    except PageNotAnInteger:
        user_list = paginator.page(1)
    except:
        user_list = paginator.page(paginator.num_pages)

    return render(request,"page.html",{"user_list":user_list,
                                       "paginator":paginator,
                                       "page_range":pageRange,        # 此處自定義一個分頁段
                                       "currentPage":currentPage})

前端分頁代碼只需要將paginator.page_range改為page_range其他地方不需要動.

        {% for item in page_range %}
            {% if item == currentPage %}
                li class="page-item active">a class="page-link" href="./page?id={{ item }}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >{{ item }}/a>/li>
            {% else %}
                li class="page-item">a class="page-link" href="./page?id={{ item }}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >{{ item }}/a>/li>
            {% endif %}
        {% endfor %}

這樣,無論有多少頁面,都能夠保證只顯示10頁。

分頁后添加刪除功能

1.刪除功能的實(shí)現(xiàn),很簡單,只需要定位得到指定的tr上,取出里面的id號碼,并發(fā)送給后端,執(zhí)行sql刪除就完事了。

head>
    meta charset="UTF-8">
    title>Title/title>
     link rel="stylesheet"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >
    script src="https://code.jquery.com/jquery-3.4.1.min.js">/script>
/head>
body>

script type="text/javascript">
    $(document).ready(function(){
      $("#but1").click(function(){
            var obj = $("#tab");          // 定位到table表格
            var check = $("table input[type=checkbox]:checked");
            check.each(function(){        // 遍歷節(jié)點(diǎn)
                var row = $(this).parent("td").parent("tr");  // 獲取選中行
                var id = row.find("[name='uid']").html();     // 取出第一行的屬性
                var name = row.find("[name='user']").html();
                alert("選中行的ID: " + id + "名字: " + name)
            });
      });
    });
/script>

table id="tab" class="table table-sm table-hover">
    thead>
        tr class="table-success">
            th>選擇/th>th> 序號/th> th> 用戶名/th> th> 用戶密碼/th>
        /tr>
    /thead>
    tbody>
        {% for article in user_list %}
            tr class="table-primary">
                td> input type="checkbox">/td>
                td name="uid">{{ article.id }}/td>
                td name="user">{{ article.username }}/td>
                td>{{ article.password }}/td>
            /tr>
        {% endfor %}
    /tbody>
/table>
.................

div>
    button id="but1" class="btn btn-danger" onclick="check()">刪除指定行/button>
/div>

實(shí)現(xiàn)模態(tài)框編輯內(nèi)容

點(diǎn)擊選中行,然后彈出模態(tài)框,并自動的獲取到該行數(shù)據(jù),編輯好以后直接用ajax發(fā)送post請求到后端處理即可。

head>
    link rel="stylesheet"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >
    script src="https://code.jquery.com/jquery-3.4.1.slim.min.js">/script>
    script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js">/script>
/head>

button type="button" id="but1" class="btn btn-success" data-toggle="modal" data-target="#staticBackdrop">彈框/button>

script type="text/javascript">
    $(document).ready(function(){
      $("#but1").click(function(){
            var obj = $("#tab");
            var edit = $("table input[type=checkbox]:checked");
            edit.each(function(){
                var row = $(this).parent("td").parent("tr");
                var id = row.find("[name='uid']").html();
                var name = row.find("[name='user']").html();
                var email = row.find("[name='email']").html();
                $("#edit_id").val(id);
                $("#edit_name").val(name);
                $("#edit_email").val(email);
            });
      });
    });
/script>
body>
table id="tab" border="1" cellspacing="0">
    thead>
        tr>
            th>選擇/th>th>用戶ID/th>th>用戶名稱/th>th>用戶郵箱/th>
        /tr>
    /thead>
    tbody>
        tr>
            td> input type="checkbox">/td>
            td name="uid"> 1001/td>
            td name="user"> lyshark/td>
            td name="email"> lyshark@123.com/td>
        /tr>
        tr>
            td> input type="checkbox">/td>
            td name="uid"> 1002/td>
            td name="user"> 搞事情/td>
            td name="email"> lyshark@123.com/td>
        /tr>
    /tbody>
/table>

div class="modal fade" id="staticBackdrop" data-backdrop="static" aria-hidden="true">
  div class="modal-dialog" role="document">
    div class="modal-content">
      div class="modal-header">
        h5 class="modal-title" id="staticBackdropLabel">編輯模式/h5>
      /div>
      div class="modal-body">
        !--主體部分-->
        div class="form-group row">
            label class="col-sm-2 col-form-label">用戶ID:/label>
            div class="col-sm-10">
              input type="text" id="edit_id" class="form-control">
            /div>

            label class="col-sm-2 col-form-label">名稱:/label>
            div class="col-sm-10">
              input type="text" id="edit_name" class="form-control">
            /div>

            label class="col-sm-2 col-form-label">郵箱:/label>
            div class="col-sm-10">
              input type="text" id="edit_email" class="form-control">
            /div>
        /div>
      /div>

      !--尾部內(nèi)容-->
      div class="modal-footer">
        button type="button" class="btn btn-secondary" data-dismiss="modal">關(guān)閉/button>
        button type="button" class="btn btn-primary">提交數(shù)據(jù)/button>
      /div>
    /div>
  /div>
/body>

完整代碼筆記

利用BootStrap框架實(shí)現(xiàn)分頁: 通過使用bootstrap框架,并配合Django自帶的分頁組件即可實(shí)現(xiàn)簡單的分頁效果.

# name: models.py
from django.db import models

class User(models.Model):
    id = models.AutoField(primary_key=True)
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)

# 插入測試數(shù)據(jù)
import random
def index(request):
    for i in range(1,1000):
        chars = []
        pasd = []
        for x in range(1,8):
            chars.append(random.choice('abcdefghijklmnopqrstuvwxyz'))
            pasd.append(random.choice('0987654321'))
        user = "".join(chars)
        pwd = "".join(pasd)
        models.User.objects.create(username=user, password=pwd)
    return HttpResponse("ok")
!--name: page.html-->
!DOCTYPE html>
html lang="en">
head>
    meta charset="UTF-8">
    title>Title/title>
     link rel="stylesheet"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >
/head>
body>
table class="table table-sm table-hover">
    thead>
        tr class="table-success">
            th> 序號/th> th> 用戶名/th> th> 用戶密碼/th>
        /tr>
    /thead>
    tbody>
        {% for article in user_list %}
            tr class="table-primary">
                td>{{ article.id }}/td>
                td>{{ article.username }}/td>
                td>{{ article.password }}/td>
            /tr>
        {% endfor %}
    /tbody>
/table>
nav class="d-flex justify-content-center" aria-label="Page navigation example">
    ul class="pagination">
        li class="page-item">a class="page-link" href="./page?id=1" rel="external nofollow"  rel="external nofollow" >首頁/a>/li>
        {% if user_list.has_previous %}
            li class="page-item">a class="page-link" href="./page?id={{ user_list.previous_page_number }}" rel="external nofollow"  rel="external nofollow" >上一頁/a>/li>
        {% else %}
            li class="page-item disabled">a class="page-link" href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >上一頁/a>/li>
        {% endif %}

        {% for item in paginator.page_range %}
            {% if item == currentPage %}
                li class="page-item active">a class="page-link" href="./page?id={{ item }}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >{{ item }}/a>/li>
            {% else %}
                li class="page-item">a class="page-link" href="./page?id={{ item }}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >{{ item }}/a>/li>
            {% endif %}
        {% endfor %}

        {% if user_list.has_next %}
            li class="page-item">a class="page-link" href="./page?id={{ user_list.next_page_number }}" rel="external nofollow"  rel="external nofollow" >下一頁/a>/li>
        {% else %}
            li class="page-item disabled">a class="page-link" href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >下一頁/a>/li>
        {% endif %}
        li class="page-item">a class="page-link" href="./page?id={{ paginator.num_pages }}" rel="external nofollow"  rel="external nofollow" >尾頁/a>/li>
    /ul>
/nav>

div style="text-align: center;" class="alert alert-dark">
   統(tǒng)計: {{ currentPage }}/{{ paginator.num_pages }} 共查詢到:{{ paginator.count }} 條數(shù)據(jù) 頁碼列表:{{ paginator.page_range }}
/div>
/body>
/html>
# name: views.py
from django.shortcuts import render,HttpResponse
from MyWeb import models
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

def page(request):
    user = models.User.objects.all()
    paginator = Paginator(user, 10)
    currentPage = int(request.GET.get("id",1))
    try:
        user_list = paginator.page(currentPage)
    except PageNotAnInteger:
        user_list = paginator.page(1)
    except:
        user_list = paginator.page(paginator.num_pages)

    return render(request,"page.html",{"user_list":user_list,
                                       "paginator":paginator,
                                       "currentPage":currentPage})
# name: urls.py
from MyWeb import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('page',views.page)
]

上方的分頁代碼還有一個不足之處,當(dāng)我們頁面中的頁碼數(shù)量過多時,默認(rèn)會將頁碼全部展示出來,整個頁面看上去很不美觀,我們可以直接在上方分頁代碼上稍加修改即可,如下代碼.

# name: views.py
from django.shortcuts import render,HttpResponse
from MyWeb import models
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

def page(request):
    user = models.User.objects.all()
    paginator = Paginator(user, 10)
    currentPage = int(request.GET.get("id",1))

    if paginator.num_pages > 15:
        if currentPage-5  1:
            pageRange = range(1,11)
        elif currentPage+5 > paginator.num_pages:
            pageRange = range(currentPage-5,paginator.num_pages)
        else:
            pageRange = range(currentPage-5,currentPage+5)
    else:
        pageRange = paginator.page_range

    try:
        user_list = paginator.page(currentPage)
    except PageNotAnInteger:
        user_list = paginator.page(1)
    except:
        user_list = paginator.page(paginator.num_pages)

    return render(request,"page.html",{"user_list":user_list,
                                       "paginator":paginator,
                                       "page_range":pageRange,        # 此處自定義一個分頁段
                                       "currentPage":currentPage})

前端分頁代碼只需要將paginator.page_range改為page_range其他地方不需要動.

        {% for item in page_range %}
            {% if item == currentPage %}
                li class="page-item active">a class="page-link" href="./page?id={{ item }}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >{{ item }}/a>/li>
            {% else %}
                li class="page-item">a class="page-link" href="./page?id={{ item }}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >{{ item }}/a>/li>
            {% endif %}
        {% endfor %}

利用layui框架實(shí)現(xiàn)分頁:

layui是一個完整的前端開發(fā)框架,利用它可以快速構(gòu)建分頁應(yīng)用,比BootStrap更加靈活.

# models.py
from django.db import models

class HostDB(models.Model):
    id = models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=64)
    hostaddr = models.CharField(max_length=64)
    hostmode = models.CharField(max_length=64)
!--name: index.html-->
!DOCTYPE html>
html lang="en">
head>
    meta charset="UTF-8">
    link rel="stylesheet"  rel="external nofollow"  rel="external nofollow" >
    script type="text/javascript" src="https://lyshark.com/cdn/layui/layui.js">/script>
/head>
body>
table class="layui-hide" id="demo">/table>

    script type="text/javascript">
    layui.use('table', function(){
      var table = layui.table;
      table.render({
          elem: '#demo',
          url:'/get_page',
          method:'get',
          toolbar: '#toolbarDemo'         // 顯示工具條
          ,request: {
                  pageName: 'pageIndex',  // 頁碼的參數(shù)名稱,默認(rèn):page
                  limitName: 'pageSize'   // 每頁數(shù)據(jù)量的參數(shù)名,默認(rèn):limit
          }
          ,response: {
                  statusName: 'code',     // 規(guī)定數(shù)據(jù)狀態(tài)的字段名稱,默認(rèn):code
                  statusCode: 0,          // 規(guī)定成功的狀態(tài)碼,默認(rèn):0
                  msgName: 'msg',         // 規(guī)定狀態(tài)信息的字段名稱,默認(rèn):msg
                  countName: 'DataCount', // 規(guī)定數(shù)據(jù)總數(shù)的字段名稱,默認(rèn):count
                  dataName: 'data'        // 規(guī)定數(shù)據(jù)列表的字段名稱,默認(rèn):data
          }
        ,cols: [[
          {type: 'checkbox', fixed: 'left'},
          {field:'id', title:'主機(jī)ID', width:100, sort: true},
          {field:'hostname', title:'主機(jī)名稱', width:120},
          {field:'hostaddr', title:'主機(jī)地址', width:120},
          {field:'hostmode', title:'主機(jī)組', width:120},
        ]]
        ,page: {
            layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'],     // 自定義分頁布局
            curr: 1,      // 設(shè)置默認(rèn)起始頁1
            groups: 10,   //只顯示10個連續(xù)頁碼,就是說顯示10個可見頁其他的省略
            first: false, // 不顯示首頁
            last: false   // 不顯示尾頁
        },
        limit: 5,
        limits: [5,10,15,20,25]
      });
    });
    /script>
/body>
/html>
# views.py

from django.shortcuts import render,HttpResponse
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
from MyWeb import models
import json

def index(request):
    return render(request,"index.html")

def get_page(request):
    data = models.HostDB.objects.all()
    dataCount = data.count()
    pageIndex = request.GET.get("pageIndex")
    pageSize = request.GET.get("pageSize")
    print("當(dāng)前索引:{} 當(dāng)前大小:{}".format(pageIndex,pageSize))
    print("所有記錄:{} 數(shù)據(jù)總條數(shù):{}".format(data,dataCount))

    # 將數(shù)據(jù)組裝成字典后放入data_list列表
    data_list,ref_data = [],[]
    for item in data:
        dict = { 'id':item.id , 'hostname':item.hostname, 'hostaddr':item.hostaddr, 'hostmode':item.hostmode }
        data_list.append(dict)

    # 使用分頁器分頁
    pageInator = Paginator(data_list,pageSize)
    context = pageInator.page(pageIndex)
    for item in context:
        ref_data.append(item)
    # 返回分頁格式
    data = { "code": 0,"msg": "ok","DataCount": dataCount,"data": ref_data }
    return HttpResponse(json.dumps(data))
# name: url.py
from MyWeb import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index),
    path('get_page/',views.get_page)
]

layui實(shí)現(xiàn)完整表格分頁:

通過使用layui框架完成的一個相對完整的表格分頁,可用于生產(chǎn)環(huán)境.

!--name: index.html-->
!DOCTYPE html>
html lang="en">
head>
    meta charset="UTF-8">
    link rel="stylesheet"  rel="external nofollow"  rel="external nofollow" >
    script type="text/javascript" src="https://lyshark.com/cdn/jquery/jquery3.js">/script>
    script type="text/javascript" src="https://lyshark.com/cdn/layui/layui.js">/script>
/head>
body>
div class="demoTable">
    div class="layui-inline">
        input class="layui-input" name="id" id="demoReload" autocomplete="off">
    /div>
        button class="layui-btn" data-type="reload">搜索/button>
/div>

script type="text/html" id="barDemo">
  a class="layui-btn layui-btn-xs" lay-event="edit">編輯/a>
  a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">刪除/a>
/script>

table class="layui-hide" id="demo" lay-filter="test">/table>

    script type="text/javascript">
    layui.use('table', function(){
      var table = layui.table;
      table.render({
          elem: '#demo',
          id: 'testReload',
          url:'/get_page',
          method:'get'
          ,request: {
                  pageName: 'pageIndex',  // 頁碼的參數(shù)名稱,默認(rèn):page
                  limitName: 'pageSize'   // 每頁數(shù)據(jù)量的參數(shù)名,默認(rèn):limit
          }
          ,response: {
                  statusName: 'code',     // 規(guī)定數(shù)據(jù)狀態(tài)的字段名稱,默認(rèn):code
                  statusCode: 0,          // 規(guī)定成功的狀態(tài)碼,默認(rèn):0
                  msgName: 'msg',         // 規(guī)定狀態(tài)信息的字段名稱,默認(rèn):msg
                  countName: 'DataCount', // 規(guī)定數(shù)據(jù)總數(shù)的字段名稱,默認(rèn):count
                  dataName: 'data'        // 規(guī)定數(shù)據(jù)列表的字段名稱,默認(rèn):data
          }
        ,cols: [[
          {type: 'checkbox', fixed: 'left'},
          {field:'id', title:'主機(jī)ID', width:100, sort: true},
          {field:'hostname', title:'主機(jī)名稱', width:120},
          {field:'hostaddr', title:'主機(jī)地址', width:120},
          {field:'hostmode', title:'主機(jī)組', width:120},
          {fixed: 'right', title:'操作', toolbar: '#barDemo', width:120}
        ]]
        ,page: {
            layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'],     // 自定義分頁布局
            curr: 1,      // 設(shè)置默認(rèn)起始頁1
            groups: 10,   // 只顯示10個連續(xù)頁碼,就是說顯示10個可見頁其他的省略
            first: false, // 不顯示首頁
            last: false   // 不顯示尾頁
        },
        limit: 5,
        limits: [5,10,15,20,25]
      });
// ------------------------------------------------------------------
// 監(jiān)聽行工具事件:也就是編輯與刪除的處理事件
      table.on('tool(test)', function(obj){
        var data = obj.data;
        if(obj.event === 'del'){
          layer.confirm('真的要刪除本行數(shù)據(jù)嗎 ?', {icon: 3,anim: 2}, function(index){
            // console.log("待刪除ID: " + obj.data['id']);
           $.ajax({
               url:"/delete_page/",
               type:"get",
               data: {"id":obj.data['id']},
               success:function (recv) {
                   layer.msg("刪除完成了..", {icon: 6});
               }
           });
            obj.del();
            layer.close(index);
          });
        } else if(obj.event === 'edit'){
          layer.prompt({ formType:2, title: "編輯表格",btn:['修改數(shù)據(jù)','關(guān)閉'],anim: 4,
              content:`div>
                            主機(jī)序號: input type="text" style='display:inline-block' id="id">br>br>
                            主機(jī)名稱: input type="text" style='display:inline-block' id="hostname">br>br>
                            主機(jī)地址: input type="text" style='display:inline-block' id="hostaddr">br>br>
                            主機(jī)屬組: input type="text" style='display:inline-block' id="hostmode">br>br>
                       /div>`,
              yes:function (index,layero)
              {
                  console.log("點(diǎn)擊yes觸發(fā)事件:" + index);
                  var id = $("#id").val();
                  var hostname = $("#hostname").val();
                  var hostaddr = $("#hostaddr").val();
                  var hostmode = $("#hostmode").val();
                  $.ajax({
                      url: "/update_page",
                      type: "get",
                      data: {"id": id,
                              "hostname": hostname,
                              "hostaddr": hostaddr,
                              "hostmode": hostmode },
                      success:function (recv) {
                        // 修改完成后,本地直接更新數(shù)據(jù),這樣就無需刷新一次了
                          obj.update({
                              hostname: hostname,
                              hostaddr: hostaddr,
                              hostmode: hostmode
                          });
                          layer.msg("修改完成了..", {icon: 6});
                          layer.close(index);
                      }
                  });
              }
          });
              $("#id").val(data.id);
              $("#hostname").val(data.hostname);
              $("#hostaddr").val(data.hostaddr);
              $("#hostmode").val(data.hostmode);
        }
      });

        // 搜索后的重載,也就是找到數(shù)據(jù)以后直接更新
      var $ = layui.$, active = {
        reload: function(){
          var demoReload = $('#demoReload');
          //執(zhí)行重載
          table.reload('testReload', {
            url:"/search_page",
            page: {
              curr: 1,
              limits: [1]
            }
            ,where: {
                hostname: demoReload.val()
            }
          });
        }
      };
    // ---------------------------------------------------------
    // 綁定搜索事件
      $('.demoTable .layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
          });
    });
    /script>
/body>
/html>
# name:views.py

from django.shortcuts import render,HttpResponse
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
from MyWeb import models
import json

def index(request):
    return render(request,"index.html")

def get_page(request):
    data = models.HostDB.objects.all()
    dataCount = data.count()
    pageIndex = request.GET.get("pageIndex")
    pageSize = request.GET.get("pageSize")
    print("當(dāng)前索引:{} 當(dāng)前大小:{}".format(pageIndex,pageSize))
    print("所有記錄:{} 數(shù)據(jù)總條數(shù):{}".format(data,dataCount))

    list = []
    res = []
    for item in data:
        dict = {}
        dict['id'] = item.id
        dict['hostname'] = item.hostname
        dict['hostaddr'] = item.hostaddr
        dict['hostmode'] = item.hostmode
        list.append(dict)

    pageInator = Paginator(list,pageSize)
    context = pageInator.page(pageIndex)
    for item in context:
        res.append(item)
    data = { "code": 0,"msg": "ok","DataCount": dataCount,"data": res }
    return HttpResponse(json.dumps(data))

def search_page(request):
    sql = request.GET.get("hostname")
    data = models.HostDB.objects.all().filter(hostname=sql)
    list = []
    for item in data:
        dict = {}
        dict['id'] = item.id
        dict['hostname'] = item.hostname
        dict['hostaddr'] = item.hostaddr
        dict['hostmode'] = item.hostmode
        list.append(dict)

    data = { "code": 0,"msg": "ok","DataCount": 1,"data": list }
    return HttpResponse(json.dumps(data))

def delete_page(request):
    get_id = request.GET.get("id")
    models.HostDB.objects.filter(id=get_id).delete()
    return render(request,"index.html")

def update_page(request):
    get_id = request.GET.get("id")
    get_hostname = request.GET.get("hostname")
    get_hostaddr = request.GET.get("hostaddr")
    get_hostmode = request.GET.get("hostmode")

    print(get_hostmode)
    obj = models.HostDB.objects.get(id=get_id)
    obj.hostname = get_hostname
    obj.hostaddr = get_hostaddr
    obj.hostmode = get_hostmode
    obj.save()
    return render(request,"index.html")
# name: urls.py

from MyWeb import views

urlpatterns = [
    path('',views.index),
    path('get_page/',views.get_page),
    path('search_page/',views.search_page),
    path('delete_page/',views.delete_page),
    path("update_page/",views.update_page)
]

自己實(shí)現(xiàn)分頁:

轉(zhuǎn)載代碼,僅用于收藏。

from urllib.parse import urlencode

class Pagination(object):
    def __init__(self,current_page,total_count,base_url,params,per_page_count=10,max_pager_count=10):
        try:
            current_page = int(current_page)
        except Exception as e:
            current_page = 1
        if current_page = 1:
            current_page = 1
        self.current_page = current_page
        # 數(shù)據(jù)總條數(shù)
        self.total_count = total_count

        # 每頁顯示10條數(shù)據(jù)
        self.per_page_count = per_page_count

        # 頁面上應(yīng)該顯示的最大頁碼
        max_page_num, div = divmod(total_count, per_page_count)
        if div:
            max_page_num += 1
        self.max_page_num = max_page_num

        # 頁面上默認(rèn)顯示11個頁碼(當(dāng)前頁在中間)
        self.max_pager_count = max_pager_count
        self.half_max_pager_count = int((max_pager_count - 1) / 2)

        # URL前綴
        self.base_url = base_url

        # request.GET
        import copy
        params = copy.deepcopy(params)
        # params._mutable = True
        get_dict = params.to_dict()
        # 包含當(dāng)前列表頁面所有的搜/索條件
        self.params = get_dict

    @property
    def start(self):
        return (self.current_page - 1) * self.per_page_count

    @property
    def end(self):
        return self.current_page * self.per_page_count

    def page_html(self):
        # 如果總頁數(shù) = 11
        if self.max_page_num = self.max_pager_count:
            pager_start = 1
            pager_end = self.max_page_num
        # 如果總頁數(shù) > 11
        else:
            # 如果當(dāng)前頁 = 5
            if self.current_page = self.half_max_pager_count:
                pager_start = 1
                pager_end = self.max_pager_count
            else:
                # 當(dāng)前頁 + 5 > 總頁碼
                if (self.current_page + self.half_max_pager_count) > self.max_page_num:
                    pager_end = self.max_page_num
                    pager_start = self.max_page_num - self.max_pager_count + 1   #倒這數(shù)11個
                else:
                    pager_start = self.current_page - self.half_max_pager_count
                    pager_end = self.current_page + self.half_max_pager_count

        page_html_list = []
        # {source:[2,], status:[2], gender:[2],consultant:[1],page:[1]}
        # 首頁
        self.params['page'] = 1
        first_page = '首頁' % (self.base_url,urlencode(self.params),)
        page_html_list.append(first_page)
        # 上一頁
        self.params["page"] = self.current_page - 1
        if self.params["page"] = 1:
            pervious_page = '上一頁' % (self.base_url, urlencode(self.params))
        else:
            pervious_page = '上一頁' % ( self.base_url, urlencode(self.params))
        page_html_list.append(pervious_page)
        # 中間頁碼
        for i in range(pager_start, pager_end + 1):
            self.params['page'] = i
            if i == self.current_page:
                temp = '%s' % (self.base_url,urlencode(self.params), i,)
            else:
                temp = '%s' % (self.base_url,urlencode(self.params), i,)
            page_html_list.append(temp)

        # 下一頁
        self.params["page"] = self.current_page + 1
        if self.params["page"] > self.max_page_num:
            self.params["page"] = self.current_page
            next_page = '下一頁' % (self.base_url, urlencode(self.params))
        else:
            next_page = '下一頁' % (self.base_url, urlencode(self.params))
        page_html_list.append(next_page)

        # 尾頁
        self.params['page'] = self.max_page_num
        last_page = '尾頁' % (self.base_url, urlencode(self.params),)
        page_html_list.append(last_page)

        return ''.join(page_html_list)

文章出處:https://www.cnblogs.com/lyshark

以上就是Django Paginator分頁器的使用示例的詳細(xì)內(nèi)容,更多關(guān)于Django Paginator分頁器的使用的資料請關(guān)注腳本之家其它相關(guān)文章!

您可能感興趣的文章:
  • Django1.11自帶分頁器paginator的使用方法
  • django的分頁器Paginator 從django中導(dǎo)入類
  • Django的分頁器實(shí)例(paginator)
  • 三步實(shí)現(xiàn)Django Paginator分頁的方法
  • Django使用paginator插件實(shí)現(xiàn)翻頁功能的實(shí)例
  • Django原生sql也能使用Paginator分頁的示例代碼
  • Django drf分頁器的使用詳解
  • Django分頁器的用法詳解
  • Django分頁器的用法你都了解嗎
  • Django 自定義分頁器的實(shí)現(xiàn)代碼

標(biāo)簽:長春 泉州 岳陽 清遠(yuǎn) 安慶 吉林 洛陽 怒江

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Django Paginator分頁器的使用示例》,本文關(guān)鍵詞  Django,Paginator,分頁,器,的,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《Django Paginator分頁器的使用示例》相關(guān)的同類信息!
  • 本頁收集關(guān)于Django Paginator分頁器的使用示例的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章