您好,登錄后才能下訂單哦!
這篇文章主要介紹了Python中如何實現(xiàn)Django頁面上展示固定的頁碼數(shù),具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
如果頁數(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é)果:
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“Python中如何實現(xiàn)Django頁面上展示固定的頁碼數(shù)”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。