Django中html里的分页显示

分页一


因为数据量过大,而又想直观便捷的查看数据,进而通过分页显示就可以完成这项工作

app中views.py

LIST=[]                #全局定义一个LIST
for i in range(100):   #数据量为100
    LIST.append(i)     #使LIST里面包含0-99个自然数

def user_list(request):
    current_page=request.GET.get('p',1)  #用户不存在默认看第一页
    current_page=int(current_page)       #使char型变为int型
    start=(current_page-1)*10            #第一页
    end=current_page*10                  #最后一页
    data=LIST[start:end]                 #使数据自动分页,每页10个数据

    all_count=len(LIST)                  # 计算LIST的长度
    count,y=divmod(all_count,10)         #divmod为算法 all_count/10,商为count,余数为y
    if y:           #y不为0
        count+=1    #页数+1
    page_list=[]
    for i in range(1,count+1):
        if i==current_page:   #i==页数
            temp='<a class="page active" href="/user_list/?p=%s">%s</a>'%(i,i)      #点击页数时,通过css使其页数栏变色
        else:
            temp='<a class="page" href="/user_list/?p=%s">%s</a>'%(i,i)
        page_list.append(temp)

    page_str=''.join(page_list)  #以空的字符串将页数连接起来
    from django.utils.safestring import mark_safe  

    page_str=mark_safe(page_str)  #使page_str为安全

    return render(request,'user_list.html',{'li':data,'page_str':page_str})

html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .pagination .page{
            display: inline-block;
            padding: 5px;
            background-color: lavender;
            color: black;
            margin: 10px;
        }
        .pagination .page .active{
            background-color: red;
        }
    </style>
</head>
<body>
    <ul>
        {% for item in li %}
            {% include 'li.html' %}
        {% endfor %}
    </ul>
    <div class="pagination">
        {{ page_str }}
    </div>

</body>
</html>

li.html

<li>{{ item }}</li>

分页二


猜你喜欢

转载自www.cnblogs.com/zhuifeng-mayi/p/9052737.html