Django分頁功能的實(shí)現(xiàn)代碼詳解
Django分頁功能的實(shí)現(xiàn)
打開命令行窗口,創(chuàng)建Django工程,使用以下命令:
django-admin startproject djpage
cd djpage
python manage.py startapp demo
使用PyCharm打開工程,在工程的同名文件夾的settings.py文件,注冊應(yīng)用,添加模板路徑,修改部分的settings.py內(nèi)容如下:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'demo.apps.DemoConfig' ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
在工程同名文件的urls.py文件,添加到應(yīng)用的視圖的路由
from django.conf.urls import url from django.contrib import admin from demo import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'page/(?P<id>\d+)/$',views.page) ]
在應(yīng)用的視圖views.py文件,編寫處理請求函數(shù),實(shí)現(xiàn)分頁顯示一個(gè)列表的內(nèi)容,這里列表也可以是查詢集
from django.shortcuts import render from django.core.paginator import Paginator # Create your views here. def page(request,id): hello_list = [{'title':'hello'},{'title':'world'}, {'title':'hello1'},{'title':'world1'}, {'title':'hello2'},{'title':'world2'}, {'title':'hello3'},{'title':'world3'}, {'title':'hello4'},{'title':'world4'}] pag = Paginator(hello_list, 2) page = pag.page(int(id)) return render(request,template_name='home.html', context={'page': page})
在工程根目錄新建templates文件夾,并創(chuàng)建一個(gè)home.html文件,代碼如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <ul> {% for item in page %} <li>{{item.title}}</li> {% endfor %} </ul> {% if page.has_previous %} <a href="/page/{{ page.previous_page_number }}" rel="external nofollow" rel="external nofollow" ><上一頁</a> {% endif %} {# 遍歷顯示頁碼的鏈接 #} {% for index in page.paginator.page_range %} {# 判斷是否是當(dāng)前頁 #} {% if index == page.number %} {{ index }} {% else %} <a href="/page/{{ index }}" rel="external nofollow" rel="external nofollow" >{{ index }}</a> {% endif %} {% endfor %} {# 判斷是否有下一頁 #} {% if page.has_next %} <a href="/page/{{ page.next_page_number }}" rel="external nofollow" rel="external nofollow" >下一頁></a> {% endif %} </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <ul> {% for item in page %} <li>{{item.title}}</li> {% endfor %} </ul> {% if page.has_previous %} <a href="/page/{{ page.previous_page_number }}" rel="external nofollow" rel="external nofollow" ><上一頁</a> {% endif %} {# 遍歷顯示頁碼的鏈接 #} {% for index in page.paginator.page_range %} {# 判斷是否是當(dāng)前頁 #} {% if index == page.number %} {{ index }} {% else %} <a href="/page/{{ index }}" rel="external nofollow" rel="external nofollow" >{{ index }}</a> {% endif %} {% endfor %} {# 判斷是否有下一頁 #} {% if page.has_next %} <a href="/page/{{ page.next_page_number }}" rel="external nofollow" rel="external nofollow" >下一頁></a> {% endif %} </body> </html>
page.paginator.page_range是頁面總數(shù)
運(yùn)行django服務(wù)器
python manage.py runserver
打開網(wǎng)頁,輸入
http://127.0.0.1:8000/page/1
顯示效果圖如下,分頁成功
知識點(diǎn)擴(kuò)展:
自定義分頁的實(shí)例代碼:
def book(request): # 從URL取參數(shù)(訪問的頁碼) page_num = request.GET.get("page") try: # 將取出的page轉(zhuǎn)換為int類型 page_num = int(page_num) except Exception as e: # 當(dāng)輸入的頁碼不是正經(jīng)數(shù)字的時(shí)候 默認(rèn)返回第一頁的數(shù)據(jù) page_num = 1 # 數(shù)據(jù)庫總數(shù)據(jù)是多少條 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 # 如果輸入的頁碼數(shù)超過了最大的頁碼數(shù),默認(rèn)返回最后一頁 if page_num > total_page: page_num = total_page # 定義兩個(gè)變量從哪里開始到哪里結(jié)束 data_start = (page_num - 1) * 10 data_end = page_num * 10 # 頁面上總共展示多少頁碼 max_page = 11 if total_page < max_page: max_page = total_page # 把從URL中獲取的page_num 當(dāng)做是顯示頁面的中間值, 那么展示的便是當(dāng)前page_num 的前五頁和后后五頁 half_max_page = max_page // 2 # 根據(jù)展示的總頁碼算出頁面上展示的頁碼從哪兒開始 page_start = page_num - half_max_page # 根據(jù)展示的總頁碼算出頁面上展示的頁碼到哪兒結(jié)束 page_end = page_num + half_max_page # 如果當(dāng)前頁減一半 比1還小, 不然頁面上會(huì)顯示負(fù)數(shù)的頁碼 if page_start <= 1: page_start = 1 page_end = max_page # 如果 當(dāng)前頁 加 一半 比總頁碼數(shù)還大, 不然頁面上會(huì)顯示比總頁碼還大的多余頁碼 if page_end >= total_page: page_end = total_page page_start = total_page - max_page + 1 # 從數(shù)據(jù)庫取值, 并按照起始數(shù)據(jù)到結(jié)束數(shù)據(jù)展示 all_book = models.Book.objects.all()[data_start:data_end] # 自己拼接分頁的HTML代碼 html_str_list = [] # # 加上首頁 html_str_list.append('<li><a href="/book/?page=1" rel="external nofollow" >首頁</a></li>') # 斷一下 如果是第一頁,就沒有上一頁 if page_num <= 1: html_str_list.append('<li class="disabled"><a href="#" rel="external nofollow" rel="external nofollow" ><span aria-hidden="true">«</span></a></li>') else: # 不是第一頁,就加一個(gè)上一頁的標(biāo)簽 html_str_list.append('<li><a href="/book/?page={}" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><span aria-hidden="true">«</span></a></li>'.format(page_num - 1)) for i in range(page_start, page_end + 1): # 如果是當(dāng)前頁就加一個(gè)active樣式類 if i == page_num: tmp = '<li class="active"><a href="/book/?page={0}" rel="external nofollow" rel="external nofollow" >{0}</a></li>'.format(i) else: tmp = '<li><a href="/book/?page={0}" rel="external nofollow" rel="external nofollow" >{0}</a></li>'.format(i) html_str_list.append(tmp) # 判斷,如果是最后一頁,就沒有下一頁 if page_num >= total_page: html_str_list.append('<li class="disabled"><a href="#" rel="external nofollow" rel="external nofollow" ><span aria-hidden="true">»</span></a></li>') else: # 不是最后一頁, 就加一個(gè)下一頁標(biāo)簽 html_str_list.append('<li><a href="/book/?page={}" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><span aria-hidden="true">»</span></a></li>'.format(page_num + 1)) # 加上尾頁 html_str_list.append('<li><a href="/book/?page={}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >尾頁</a></li>'.format(total_page)) page_html = "".join(html_str_list) return render(request, "book.html", {"all_book":all_book, "page_html":page_html})
相關(guān)文章
Python接口自動(dòng)化?之用例讀取方法總結(jié)
這篇文章主要介紹了Python接口自動(dòng)化?之用例讀取方法總結(jié),在軟件測試中,為項(xiàng)目編寫接口自動(dòng)化用例已成為測試人員常駐的測試工作。本文以python為例,基于筆者曾使用過的三種用例數(shù)據(jù)讀取方法:xlrd、pandas、yaml,下面簡要地介紹下它們的使用方法及簡單分析2022-06-06python網(wǎng)絡(luò)編程學(xué)習(xí)筆記(九):數(shù)據(jù)庫客戶端 DB-API
這篇文章主要介紹了python 數(shù)據(jù)庫客戶端 DB-API的相關(guān)資料,需要的朋友可以參考下2014-06-06Python3進(jìn)行表格數(shù)據(jù)處理的示例詳解
數(shù)據(jù)處理是一個(gè)當(dāng)下非常熱門的研究方向,通過對于大型實(shí)際場景中的數(shù)據(jù)進(jìn)行建模,可以用于預(yù)測下一階段可能出現(xiàn)的情況。本文就來聊聊Python3進(jìn)行表格數(shù)據(jù)處理的相關(guān)操作,需要的可以參考一下2023-03-03python異步Web框架sanic的實(shí)現(xiàn)
這篇文章主要介紹了python異步Web框架sanic的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04Python基礎(chǔ)類繼承重寫實(shí)現(xiàn)原理解析
這篇文章主要介紹了Python基礎(chǔ)類繼承重寫實(shí)現(xiàn)原理解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04Boston數(shù)據(jù)集預(yù)測放假及應(yīng)用優(yōu)缺點(diǎn)評估
這篇文章主要為大家介紹了Boston數(shù)據(jù)集預(yù)測放假及應(yīng)用優(yōu)缺點(diǎn)評估,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10ID3決策樹以及Python實(shí)現(xiàn)詳細(xì)過程
決策樹是我本人非常喜歡的機(jī)器學(xué)習(xí)模型,非常直觀容易理解,并且和數(shù)據(jù)結(jié)構(gòu)的結(jié)合很緊密,下面這篇文章主要給大家介紹了關(guān)于ID3決策樹以及Python實(shí)現(xiàn)的相關(guān)資料,需要的朋友可以參考下2024-01-01