效果圖: 方法如下: 1.簡單版(較繁瑣但是直觀): 1.1 定義資料庫模型(models.py)中添加表 class ProductSample(models.Model): # 示例商品表 id = models.AutoField(db_column='ID', primary_key=Tru ...
效果圖:
方法如下:
1.簡單版(較繁瑣但是直觀):
1.1 定義資料庫模型(models.py)中添加表
class ProductSample(models.Model):
# 示例商品表
id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase.
item_id = models.CharField(verbose_name="用戶ID",max_length=255, blank=True, null=True)
title = models.TextField(verbose_name="標題",blank=True, null=True)
pict_url = models.CharField(verbose_name="商品圖片鏈接",max_length=255, blank=True, null=True)
category = models.TextField(verbose_name="類別",blank=True, null=True)
brand_id = models.CharField(verbose_name="品牌ID",max_length=255, blank=True, null=True)
seller_id = models.CharField(verbose_name="賣家ID",max_length=255, blank=True, null=True)
def __str__(self):
return self.title
# class Meta:
# verbose_name = '商品信息'
# verbose_name_plural = verbose_name
class Meta:
managed = False
db_table = 'product_sample'
1.2 路由(urls.py)中添加路徑
path("home/", views.home,name='home'), #主頁面
1.3 在視圖中(view.py)添加如下代碼
from .models import ProductSample #導入表
from django.utils.safestring import mark_safe
"""
需要修改如下代碼(替換為自己的表):
#數據總條數
total_count = 替換.objects.all().order_by('id').count()
#MySQL上獲取數據
documents = 替換.objects.all().order_by('id')[start:end] # 指定按 id 欄位排序
"""
def home(request):
"""主頁面"""
# 分頁器設計
page = int(request.GET.get('page',1))
size = 10 #每頁顯示10條
start = (page - 1)*size
end = page*size
#數據總條數
total_count = ProductSample.objects.all().order_by('id').count()
#總頁碼
total_page_count, div = divmod(total_count, size)
if div:
total_page_count +=1
#MySQL上獲取數據
documents = ProductSample.objects.all().order_by('id')[start:end] # 指定按 id 欄位排序
#計算初當前頁的前五頁和後五頁
plus = 5
if total_page_count <= 2 * plus + 1:
#資料庫中的數據較少,沒有達到11頁
start_page = 1
end_page = total_page_count
else:
#資料庫中的數據較多 大於11頁
#當前頁<5時
if page <= plus:
start_page = 1
end_page = 2 * plus
else:
#當前頁>5
#當前頁+5總頁碼
if (page + plus ) > total_page_count:
start_page = total_page_count - 2 * plus
end_page = total_page_count
else:
start_page = page - plus
end_page = page + plus
#頁碼
page_str_list = []
#首頁
page_str_list.append('<li><a href ="?page={}">首頁</a></li>'.format(1))
#上一頁
if page > 1:
prev = '<li><a href ="?page={}" aria-label="Previous"><span aria-hidden="true">«</span></a></li>'.format(page-1)
else:
prev = '<li><a href ="?page={}" aria-label="Previous"><span aria-hidden="true">«</span></a></li>'.format(1)
page_str_list.append(prev)
#頁面
for i in range(start_page,end_page+1):
if i== page:
ele = '<li class="active"><a href ="?page={}">{}</a></li>'.format(i,i)
else:
ele = '<li><a href ="?page={}">{}</a></li>'.format(i,i)
page_str_list.append(ele)
#下一頁
if page < total_page_count:
next_page = '<li><a href ="?page={}" aria-label="Next"><span aria-hidden="true">»</span></a></li>'.format(page+1)
else:
next_page = '<li><a href ="?page={}" aria-label="Next"><span aria-hidden="true">»</span></a></li>'.format(total_page_count)
page_str_list.append(next_page)
#尾頁
page_str_list.append('<li><a href ="?page={}">尾頁</a></li>'.format(total_page_count))
#搜索
search_string ="""
<li>
<form style="display: inline-block;" method="get">
<div class="input-group" style="width: 200px;display: inline-block;">
<input name="page"
style="position: relative;float: left;display: inline-block;width: 80px;border-radius: 0;"
type="text" class="form-control" placeholder="頁碼">
<span class="input-group-btn">
<button style="border-radius: 0;" class="btn btn-default" type="submit">跳轉</button>
</span>
</div>
</form>
</li>
"""
page_str_list.append(search_string)
page_string = mark_safe("".join(page_str_list))
return render(request,'home/home.html',locals())
1.4 html頁面使用分頁器
<div>
{% for d in documents %}
{{ d.pict_url }}
{{ d.title }}
<p>價格:${{ random_num }}</p>
{% endfor %}
<nav aria-label="Page navigation">
<ul class="pagination">
{{ page_string }}
</ul>
</nav>
</div>
{% endblock %}
2 高級版(設置組件,可用於其他數據的分頁)
2.1 自定義分頁組件(在app裡面新建一個utils目錄,在utils裡面新建一個pagination.py文件)將下麵代碼添加到pagination.py文件中,使用說明如下:
缺點:搜索+分頁器時,不能將搜索的情況保留(下麵有改進版,按需設計)
"""
自定義的分頁組件,以後想要使用這個分頁組件,需要做如下幾件事:
#在視圖函數中:
from home.utils.pagination import Pagination
def home(request):
# 1.根據自己的情況去篩選自己的數據
queryset = ProductSample.objects.all()
# 2.實例化分頁對象
page_object = Pagination(request,queryset)
page_queryset = page_object.page_queryset #分頁後的數據
page_string = page_object.html() #頁碼
return render(request,'home/home.html',locals())
#在HTML頁面中:
{% for d in page_queryset %}
<h4> {{ d.title }} </h4>
{% endfor %}
<ul class="pagination">
{{ page_string }}
</ul>
"""
from django.utils.safestring import mark_safe
class Pagination(object):
def __init__(self,request,queryset,size = 10, plus=5, page_param="page"):
"""
:param request: 請求的對象
:param queryset: 符合條件的數據(對該數據進行分頁處理)
:param size:每頁顯示多少條數據
:param plus:顯示當前頁的前或後幾頁(頁碼)
:param page_param:在URL中傳遞的獲取分頁的參數,例如:/home/?page=12
"""
page = request.GET.get(page_param, "1")
if page.isdecimal():
page = int(page)
else:
page = 1
self.page = page
self.size = size # 每頁顯示10條
self.start = (page - 1) * size
self.end = page * size
self.page_queryset =queryset[self.start:self.end]
# 數據總條數
total_count = queryset.count()
# 總頁碼
total_page_count, div = divmod(total_count, size)
if div:
total_page_count += 1
self.total_page_count = total_page_count
self.plus = plus
def html(self):
# 計算初當前頁的前五頁和後五頁
if self.total_page_count <= 2 * self.plus + 1:
# 資料庫中的數據較少,沒有達到11頁
start_page = 1
end_page = self.total_page_count
else:
# 資料庫中的數據較多 大於11頁
# 當前頁<5時
if self.page <= self.plus:
start_page = 1
end_page = 2 * self.plus
else:
# 當前頁>5
# 當前頁+5總頁碼
if (self.page + self.plus) > self.total_page_count:
start_page = self.total_page_count - 2 * self.plus
end_page = self.total_page_count
else:
start_page = self.page - self.plus
end_page = self.page + self.plus
# 頁碼
page_str_list = []
# 首頁
page_str_list.append('<li><a href ="?page={}">首頁</a></li>'.format(1))
# 上一頁
if self.page > 1:
prev = '<li><a href ="/home/?page={}" aria-label="Previous"><span aria-hidden="true">«</span></a></li>'.format(
self.page - 1)
else:
prev = '<li><a href ="?page={}" aria-label="Previous"><span aria-hidden="true">«</span></a></li>'.format(
1)
page_str_list.append(prev)
# 頁面
for i in range(start_page, end_page + 1):
if i == self.page:
ele = '<li class="active"><a href ="?page={}">{}</a></li>'.format(i, i)
else:
ele = '<li><a href ="?page={}">{}</a></li>'.format(i, i)
page_str_list.append(ele)
# 下一頁
if self.page < self.total_page_count:
next_page = '<li><a href ="?page={}" aria-label="Next"><span aria-hidden="true">»</span></a></li>'.format(
self.page + 1)
else:
next_page = '<li><a href ="?page={}" aria-label="Next"><span aria-hidden="true">»</span></a></li>'.format(
self.total_page_count)
page_str_list.append(next_page)
# 尾頁
page_str_list.append('<li><a href ="?page={}">尾頁</a></li>'.format(self.total_page_count))
# 搜索
search_string = """
<li>
<form style="display: inline-block;" method="get">
<div class="input-group" style="width: 200px;display: inline-block;">
<input name="page"
style="position: relative;float: left;display: inline-block;width: 80px;border-radius: 0;"
type="text" class="form-control" placeholder="頁碼">
<span class="input-group-btn">
<button style="border-radius: 0;" class="btn btn-default" type="submit">跳轉</button>
</span>
</div>
</form>
</li>
"""
page_str_list.append(search_string)
page_string = mark_safe("".join(page_str_list))
return page_string
3 高級版的升級(搜索+分頁)
修改pagination.py文件。原理:保留參數
問題:跳轉不能實現搜索的跳轉,處理辦法,結合Ajax來實現。
"""
自定義的分頁組件,以後想要使用這個分頁組件,需要做如下幾件事:
在視圖函數中:
from home.utils.pagination import Pagination
def home(request):
# 1.根據自己的情況去篩選自己的數據
queryset = ProductSample.objects.all()
# 2.實例化分頁對象
page_object = Pagination(request,queryset)
page_queryset = page_object.page_queryset #分頁後的數據
page_string = page_object.html() #頁碼
return render(request,'home/home.html',locals())
#在HTML頁面中:
{% for d in page_queryset %}
<h4> {{ d.title }} </h4>
{% endfor %}
<ul class="pagination">
{{ page_string }}
</ul>
"""
from django.utils.safestring import mark_safe
class Pagination(object):
def __init__(self,request,queryset,size = 10, plus=5, page_param="page"):
"""
:param request: 請求的對象
:param queryset: 符合條件的數據(對該數據進行分頁處理)
:param size:每頁顯示多少條數據
:param plus:顯示當前頁的前或後幾頁(頁碼)
:param page_param:在URL中傳遞的獲取分頁的參數,例如:/home/?page=12
"""
from django.http.request import QueryDict
import copy
query_dict = copy.deepcopy(request.GET)
query_dict._mutable = True
self.query_dict = query_dict
self.page_param = page_param
page = request.GET.get(page_param, "1")
if page.isdecimal():
page = int(page)
else:
page = 1
self.page = page
self.size = size # 每頁顯示10條
self.start = (page - 1) * size
self.end = page * size
self.page_queryset =queryset[self.start:self.end]
# 數據總條數
total_count = queryset.count()
# 總頁碼
total_page_count, div = divmod(total_count, size)
if div:
total_page_count += 1
self.total_page_count = total_page_count
self.plus = plus
def html(self):
# 計算初當前頁的前五頁和後五頁
if self.total_page_count <= 2 * self.plus + 1:
# 資料庫中的數據較少,沒有達到11頁
start_page = 1
end_page = self.total_page_count
else:
# 資料庫中的數據較多 大於11頁
# 當前頁<5時
if self.page <= self.plus:
start_page = 1
end_page = 2 * self.plus
else:
# 當前頁>5
# 當前頁+5總頁碼
if (self.page + self.plus) > self.total_page_count:
start_page = self.total_page_count - 2 * self.plus
end_page = self.total_page_count
else:
start_page = self.page - self.plus
end_page = self.page + self.plus
# 頁碼
page_str_list = []
self.query_dict.setlist(self.page_param,[1])
# 首頁
page_str_list.append('<li><a href ="?{}">首頁</a></li>'.format(self.query_dict.urlencode()))
# 上一頁
if self.page > 1:
self.query_dict.setlist(self.page_param, [self.page - 1])
prev = '<li><a href ="?{}" aria-label="Previous"><span aria-hidden="true">«</span></a></li>'.format(
self.query_dict.urlencode())
else:
self.query_dict.setlist(self.page_param, [1])
prev = '<li><a href ="?{}" aria-label="Previous"><span aria-hidden="true">«</span></a></li>'.format(
self.query_dict.urlencode())
page_str_list.append(prev)
# 頁面
for i in range(start_page, end_page + 1):
if i == self.page:
self.query_dict.setlist(self.page_param, [i])
ele = '<li class="active"><a href ="?{}">{}</a></li>'.format(self.query_dict.urlencode(), i)
else:
self.query_dict.setlist(self.page_param, [i])
ele = '<li><a href ="?{}">{}</a></li>'.format(self.query_dict.urlencode(), i)
page_str_list.append(ele)
# 下一頁
if self.page < self.total_page_count:
self.query_dict.setlist(self.page_param, [self.page + 1])
next_page = '<li><a href ="?{}" aria-label="Next"><span aria-hidden="true">»</span></a></li>'.format(
self.query_dict.urlencode())
else:
self.query_dict.setlist(self.page_param, [self.total_page_count])
next_page = '<li><a href ="?{}" aria-label="Next"><span aria-hidden="true">»</span></a></li>'.format(
self.query_dict.urlencode())
page_str_list.append(next_page)
# 尾頁
self.query_dict.setlist(self.page_param, [self.total_page_count])
page_str_list.append('<li><a href ="?{}">尾頁</a></li>'.format(self.query_dict.urlencode()))
# 搜索
search_string = """
<li>
<form style="display: inline-block;" method="get">
<div class="input-group" style="width: 200px;display: inline-block;">
<input name="page"
style="position: relative;float: left;display: inline-block;width: 80px;border-radius: 0;"
type="text" class="form-control" placeholder="頁碼">
<span class="input-group-btn">
<button style="border-radius: 0;" class="btn btn-default" type="submit">跳轉</button>
</span>
</div>
</form>
</li>
"""
page_str_list.append(search_string)
page_string = mark_safe("".join(page_str_list))
return page_string
不甘平凡,努力活出自己的人生!