Django分頁功能的實現(xiàn)代碼詳解
Django分頁功能的實現(xiàn)
打開命令行窗口,創(chuàng)建Django工程,使用以下命令:
django-admin startproject djpage
cd djpage
python manage.py startapp demo

使用PyCharm打開工程,在工程的同名文件夾的settings.py文件,注冊應用,添加模板路徑,修改部分的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文件,添加到應用的視圖的路由
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) ]

在應用的視圖views.py文件,編寫處理請求函數(shù),實現(xiàn)分頁顯示一個列表的內(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)建一個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 %}
{# 判斷是否是當前頁 #}
{% 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 %}
{# 判斷是否是當前頁 #}
{% 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ù)

運行django服務器
python manage.py runserver

打開網(wǎng)頁,輸入
http://127.0.0.1:8000/page/1
顯示效果圖如下,分頁成功

知識點擴展:
自定義分頁的實例代碼:
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:
# 當輸入的頁碼不是正經(jīng)數(shù)字的時候 默認返回第一頁的數(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ù),默認返回最后一頁
if page_num > total_page:
page_num = total_page
# 定義兩個變量從哪里開始到哪里結(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 當做是顯示頁面的中間值, 那么展示的便是當前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
# 如果當前頁減一半 比1還小, 不然頁面上會顯示負數(shù)的頁碼
if page_start <= 1:
page_start = 1
page_end = max_page
# 如果 當前頁 加 一半 比總頁碼數(shù)還大, 不然頁面上會顯示比總頁碼還大的多余頁碼
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:
# 不是第一頁,就加一個上一頁的標簽
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):
# 如果是當前頁就加一個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:
# 不是最后一頁, 就加一個下一頁標簽
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})
相關文章
python網(wǎng)絡編程學習筆記(九):數(shù)據(jù)庫客戶端 DB-API
這篇文章主要介紹了python 數(shù)據(jù)庫客戶端 DB-API的相關資料,需要的朋友可以參考下2014-06-06
Boston數(shù)據(jù)集預測放假及應用優(yōu)缺點評估
這篇文章主要為大家介紹了Boston數(shù)據(jù)集預測放假及應用優(yōu)缺點評估,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-10-10

