[django]分页思路

梳理分页思路

构造数据
    获取随机字符串作为密码

分页算法

显示页码
处理上一页,下一页

bootstrap修改样式: http://v3.bootcss.com/components/#pagination
views.py

from django.shortcuts import render


# Create your views here.


# 分页算法

# 获取数据 root1:root123
def get_random_str(len_str):
    import string
    import random
    letters_nums = string.ascii_letters + string.digits
    res = random.sample(letters_nums, len_str)
    return ''.join(res)


def get_user_list_data():
    user_list = []
    for i in range(100):
        res = '%s%s:%s' % ('root', i, get_random_str(10))
        user_list.append(res)
    return user_list


user_list = get_user_list_data()


def index(request):
    # 分页算法
    # 1  0-10
    # 2  10-20
    per_page = 10
    cur_page = int(request.GET.get("p"))
    start = (cur_page - 1) * per_page
    end = cur_page * per_page

    # 页码
    page_num = len(user_list) // per_page

    ##上一页下一页
    if cur_page > 1:
        prev_page = cur_page - 1
    else:
        prev_page = 1
    if cur_page < page_num:
        next_page = cur_page + 1
    else:
        next_page = page_num
    return render(request, 'app01/index.html',
                  {'user_list': user_list[start:end], 'page_num': range(1, page_num + 1), 'prev_page': prev_page,
                   'next_page': next_page})

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div>
    <h1>分页</h1>
    {% for row in user_list %}
        {{ row }} <br>
    {% endfor %}
</div>

<div>
    <a href="?p={{ prev_page }}">上一页</a>
    {% for row in page_num %}
        <a href="?p={{ row }}">{{ row }}</a>
    {% endfor %}
    <a href="?p={{ next_page }}">下一页</a>
</div>

<div>
    <nav aria-label="Page navigation">
        <ul class="pagination">
            <li>
                <a href="?p={{ prev_page }}" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                </a>
            </li>
            {% for row in page_num %}
                <li><a href="?p={{ row }}">{{ row }}</a></li>
            {% endfor %}
            <li>
                <a href="?p={{ next_page }}" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                </a>
            </li>
        </ul>
    </nav>
</div>
</body>
</html>
posted @ 2018-06-24 11:16  mmaotai  阅读(120)  评论(0编辑  收藏  举报