HTML代码




    
    Title
    
    
    
    


图书列表

{% for book in book_list %} {% endfor %}
ID 名字 出版社 价格
{{ book.id }} {{ book.title }} {{ book.publisher.name }} {{ book.price }}
{#重点位置#}

Python 代码

def book_list(request):
    # 每一页显示数量
    per_page = 7

    # 总数据
    total_count = models.Book.objects.all().count()

    # 总共需要多少页显示数据
    total_page, m = divmod(total_count, per_page)
    if m:
        total_page += 1

    # 从URL中取参数,当没有page时,page_num为1,当page_num大于总页数时,赋于最后一页,当page为字符时,异常出错时,为1值
    try:
        page_num = request.GET.get("page")
        page_num = int(page_num)
        if page_num > total_page:
            page_num = total_page
        elif page_num < 1:
            page_num =1
    except Exception as e:
        page_num = 1

    #定义两个变量,截取数据
    data_start = (page_num-1)*per_page
    data_end = page_num*per_page

    #页面上总共展示多少页面
    max_page =11
    if total_page < max_page:
        max_page = total_page

    half_max_page = max_page//2    #结果为5,即左右各5页

    # 页面上展示的面码从那儿结束
    page_end = page_num + half_max_page

    #页面上展示的页码从那儿开始
    page_start = page_num - half_max_page

    #如果当前面减一半比1还小
    if page_start <= 1:
        page_start = 1
        page_end = max_page

    #如果当前页大于总页数
    if page_end >= total_page:
        page_end = total_page
        page_start = total_page-max_page+1

    #在后台拼接分页的html
    html_str_list = []
    for i in range(page_start, page_end+1):
        #为当前加一个active样式
        if i == page_num:
            tmp = '
  • {0}
  • '.format(i) else: tmp = '
  • {0}
  • '.format(i) html_str_list.append(tmp) #将所有li的html文件拼接连接成一块 page_html = "".join(html_str_list) #print(page_html) all_book = models.Book.objects.all()[data_start:data_end] return render(request,"book.html",{"book_list":all_book,"page_html":page_html,"total_page":total_page})

    展示效果

    Django 之 分页功能_第1张图片