欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python Django 頁面上展示固定的頁碼數(shù)實現(xiàn)代碼

 更新時間:2019年08月21日 10:40:25   作者:Sch01aR#  
這篇文章主要介紹了Python Django 頁面上展示固定的頁碼數(shù)實現(xiàn)代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

如果頁數(shù)太多的話,全部顯示在頁面上就會顯得很冗雜

可以在頁面中顯示規(guī)定的頁碼數(shù)

例如:

book_list.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>書籍列表</title>
  <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css" rel="external nofollow" >
</head>
<body>
 
<div class="container">
 
  <table class="table table-bordered">
    <thead>
    <tr>
      <th>序號</th>
      <th>id</th>
      <th>書名</th>
    </tr>
    </thead>
    <tbody>
    {% for book in books %}
      <tr>
        <td>{{ forloop.counter }}</td>
        <td>{{ book.id }}</td>
        <td>{{ book.title }}</td>
      </tr>
    {% endfor %}
 
    </tbody>
  </table> 
  <nav aria-label="Page navigation">
    <ul class="pagination">
      <li>
        <a href="#" rel="external nofollow" rel="external nofollow" aria-label="Previous">
          <span aria-hidden="true">«</span>
        </a>
      </li>
      <li>
        {{ page_html|safe }}
      </li>
      <li>
        <a href="#" rel="external nofollow" rel="external nofollow" aria-label="Next">
          <span aria-hidden="true">»</span>
        </a>
      </li>
    </ul>
  </nav> 
</div> 
</body>
</html>

views.py:

from django.shortcuts import render
from app01 import models 
def book_list(request):
  # 從 URL 中取參數(shù)
  page_num = request.GET.get("page")
  print(page_num, type(page_num))
  page_num = int(page_num)
 
  # 定義兩個變量保存數(shù)據(jù)從哪兒取到哪兒
  data_start = (page_num-1)*10
  data_end = page_num*10
 
  # 書籍總數(shù)
  total_count = models.Book.objects.all().count()
 
  # 每一頁顯示多少條數(shù)據(jù)
  per_page = 10
 
  # 總共需要多少頁碼來顯示
  total_page, m = divmod(total_count, per_page)
 
  # 頁面上最多展示的頁碼
  max_page = 11
  half_max_page = max_page // 2
 
  # 頁面上展示的頁碼的開始頁
  page_start = page_num - half_max_page
  # 頁面上展示的頁碼的結(jié)束頁
  page_end = page_num + half_max_page
 
  # 如果當(dāng)前頁減一半比 1 小
  if page_start <= 1:
    page_start = 1
    page_end = max_page
  # 如果當(dāng)前頁加一半比總頁碼還大
  if page_end > total_page:
    page_end = total_page
    page_start = total_page - max_page + 1
 
  # 如果還有數(shù)據(jù)
  if m:
    total_page += 1
 
  all_book = models.Book.objects.all()[data_start:data_end]
 
  # 拼接 html 的分頁代碼
  html_list = []
  for i in range(page_start, page_end+1):
    tmp = '<li><a href="/book_list/?page={0}" rel="external nofollow" >{0}</a></li>'.format(i)
    html_list.append(tmp)
 
  page_html = "".join(html_list)
 
  return render(request, "book_list.html", {"books": all_book, "page_html": page_html})

運行結(jié)果:

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論