django分页

django分页二

2017-07-18  本文已影响0人  赖三石

urls.py同分页一

views.py

# encoding=utf-8
from django.shortcuts import render

# Create your views here.


def index(request):
    #模拟数据,列表生成式
    a_list = [i for i in range(1, 105)]

    #获取当前页, 注意获取时是字符串,要转换为int
    current_page = request.GET.get('p', 1)
    current_page = int(current_page)

    #数据切片
    #data = a_list[:10]
    #data = a_list[20: 30]

    #每页显示10条数据,并且得与current_page发生关系
    start = (current_page-1) * 10
    end = current_page * 10
    data = a_list[start: end]

    ########页码########
    #total_count:数据总条数
    #page_num:总页数
    total_count = len(a_list)
    page_num, y = divmod(total_count, 10)
    #y为余数,y=0为假
    if y:
        page_num += 1
  
    page_html_list = []
    for j in range(1, page_num+1):
        page_html = '<a href="/index/?p=%s">%s</a>' % (j, j)
        page_html_list.append(page_html)

    return render(request, 'index.html', {'data': data, 'page': page_html_list})

template

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<ul>
    {% for d in data %}
        <li>{{ d }}</li>
    {% endfor %}
</ul>

{% for i in page %}
{{ i|safe }}
{% endfor %}
</body>
</html>

注意:{{ i|safe }}因为要保护模板,后台传过来的都按字符串显示<a>...</a>
如果要按特殊显示,必须确认传过来的数据安全,加上 ...|safe

上一篇下一篇

猜你喜欢

热点阅读