1. 程式人生 > >django 分頁

django 分頁

data 結束 utf-8 切片 信息展示 def itl true django 分頁

view.py

# 分頁
def paging(request):
    # 叢數據庫表取出來的數據總數
    count_data = len(message.objects.all())
    # 當前頁數,因為url的傳值是字符串,所以需要轉成整形
    page = int(request.GET.get("page"))
    # 每頁顯示3條數據
    per_page_count = 3
    # 開始的索引
    start_dat = (page - 1) * per_page_count
    # 結束的索引
    end_data = page * per_page_count
    # 數據切片
    data = message.objects.all()[start_dat:end_data]
    # 上一頁
    prev_pager = page - 1
    # 下一頁
    next_pager = page + 1

    return render(request,"paging.html",{"list":data,"prev_pager":prev_pager,"next_pager":next_pager})

  

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>分頁</title>
</head>
<body>
  <h1>信息展示</h1>
    <table>
    <tr>
        <th>用戶名</th>
        <th>密碼</th>
    </tr>
    {% for line in list %}
    <tr>
        <td>{{line.username}}</td>
        <td>{{line.password}}</td>
    </tr>
    {% endfor %}
    </table>
    <a href="{% url "paging" %}?page={{ prev_pager }}">上一頁</a>
    <a href="{% url "paging" %}?page={{ next_pager }}">下一頁</a>
</body>
</html>

  

urls.py

 url(r^paging.html$, views.paging,name=paging),

django 分頁