1. 程式人生 > >Django 實現分頁顯示

Django 實現分頁顯示

總體思路:

從資料庫取出資料,根據事先定義的每頁顯示的數量,進行分頁計算,得到頁數,構造html,返回給前端解析顯示。

後端python操作程式碼

#操作資料庫進行分頁
    page = common.try_int(page, 1)
    perpage = 5  #每頁顯示的資料數量

    start = (page - 1)*perpage
    end = page*perpage

    count = models.Host.objects.all().count() #從資料庫拿到資料數量
    result = models.Host.objects.all()[start:end]

    tmp_pages = divmod(count, perpage)
    if tmp_pages[1] == 0:
        all_pages = tmp_pages[0]
    else:
        all_pages = tmp_pages[0] + 1
    page_html = []
    first_html = "<a href='/index/%d'>首頁</a>" %(1,)
    page_html.append(first_html)

    if page == 1: #頁面邊界檢測
        pre_next_html = "<a href='/index/%d'>上一頁</a>" %(1,)
    else:
        pre_next_html = "<a href='/index/%d'>上一頁</a>" %(page-1,)
    page_html.append(pre_next_html)

    for i in range(all_pages):
        if i+1 == page:
            tmp_html = "<a style='color:red;' href='/index/%d'>%d</a>" %(i+1, i+1)
        else:
            tmp_html = "<a href='/index/%d'>%d</a>" %(i+1, i+1)
        page_html.append(tmp_html)

    if page == all_pages:
        nnext_html = "<a href='/index/%d'>下一頁</a>" %(all_pages,)
    else:
        nnext_html = "<a href='/index/%d'>下一頁</a>" %(page+1,)
    page_html.append(nnext_html)

    last_html = "<a href='/index/%d'>尾頁</a>" %(all_pages,)
    page_html.append(last_html)

    page = mark_safe(''.join(page_html))
    ret = {'data':result, 'count':count, 'pages':all_pages, 'list':page}
    return render_to_response("index.html", ret)   #返回資料,用模板語言解析拿到資料

前端解析部分:
    <table border="1">
    {% for item in data %}
        <tr>
            <td>{{item.HostName}}</td>
            <td>{{item.IP}}</td>
        </tr>

    {% endfor %}
    </table>
    <div>總條數:{{count}}</div>
    <div>總頁數: {{pages}}</div>
    <div>
        <a href="/index/1">首頁</a>
    </div>
{{list}}   #f分頁列表