Python Django 簡單分頁的實現(xiàn)代碼解析
這篇文章主要介紹了Python Django 簡單分頁的實現(xiàn)代碼解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
models.py:
from django.db import models class Book(models.Model): title = models.CharField(max_length=32) def __str__(self): return self.title class Meta: db_table = "books"
批量創(chuàng)建 106 條數(shù)據(jù)
import os if __name__ == '__main__': os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite3.settings") import django django.setup() from app01 import models # 106 個書籍對象 objs = [models.Book(title="《Python 的故事第{}版》".format(i)) for i in range(116)] # 在數(shù)據(jù)庫中批量創(chuàng)建, 10 次一提交 models.Book.objects.bulk_create(objs, 10)
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) if m: total_page += 1 all_book = models.Book.objects.all()[data_start:data_end] # 拼接 html 的分頁代碼 html_list = [] for i in range(1, total_page+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})
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"> {{ page_html|safe }} </ul> </nav> </div> </body> </html>
運行結(jié)果:
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python dataframe實現(xiàn)統(tǒng)計行列中零值的個數(shù)
這篇文章主要介紹了python dataframe實現(xiàn)統(tǒng)計行列中零值的個數(shù),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02python執(zhí)行js腳本報錯CryptoJS is not defined問題
這篇文章主要介紹了python執(zhí)行js腳本報錯CryptoJS is not defined問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05精選39道Python數(shù)據(jù)分析面試題提早備戰(zhàn)金三銀四
這篇文章主要為大家介紹了39道Python數(shù)據(jù)分析的面試題問答攻略幫助大家提早備戰(zhàn)金三銀四,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多精進,早日度過寒冬2023-12-12python日記(使用TCP實現(xiàn)的對話客戶端和服務(wù)器)
這篇文章主要為大家介紹了python使用TCP實現(xiàn)的對話客戶端和服務(wù)器實現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-03-03