Django 高階篇 分頁

2022-07-13 10:03:07 字數 2923 閱讀 7912

定義乙個分頁類,封裝起來,儲存到目錄下面方便呼叫:pagination.py

具體完整**:

from django.utils.safestring import

mark_safe

#分頁類

class

page(object):

def__init__(self,current_page,data_count,per_page_count=10,page_num=11):

"""current_page:當前頁

data_count:資料量

per_page_count:每頁顯示多少行資料

page_num: 顯示固定多少行頁碼

"""self.current_page =current_page

self.data_count =data_count

self.per_page_count =per_page_count

self.page_num =page_num

@property

defstart(self):

"""切片起始值

"""return (self.current_page-1) *self.per_page_count

@property

defend(self):

"""切片末尾值

"""return self.current_page *self.per_page_count

@property

deftotal_count(self):

"""總頁碼:v

餘數:y

total_count返回的就是總頁碼值

"""v,y=divmod(self.data_count,self.per_page_count)

ify:

v +=1

return

v

defpage_str(self,base_url):

"""生成頁碼,上下頁, 跳轉等功能

base_url:接收使用者的url

"""self.base_url=base_url

"""page_list:頁碼列表

"""page_list =

if self.total_count

start_index=1end_index=self.total_count +1

else

:

if self.current_page <= (self.page_num +1)/2:

start_index = 1end_index = self.page_num +1

else

: start_index= self.current_page - (self.page_num -1)/2end_index= self.current_page +(self.page_num +1)/2

if self.current_page + (self.page_num -1)/2 >self.total_count:

start_index = self.current_page -self.page_num +1end_index = self.total_count +1

#if self.current_page == 1:

prev = '

'else

: prev='

' %(self.base_url,self.current_page - 1)

#迴圈的總頁碼

for i in

range(int(start_index),int(end_index)):

if i ==self.current_page:

temp = '

%s' %(self.base_url, i, i)

else

: temp= '

%s' %(self.base_url,i,i)

#if self.current_page ==self.total_count:

next = '

'else

: next = '

' % (self.base_url, self.current_page + 1)

#跳轉指定頁碼

jump="""

""" %(self.base_url)

#拼接字串

page_str= ""

.join(page_list)

page_str=mark_safe(page_str)

return page_str

views檢視:—呼叫封裝好的類

返回的page_str字串到user_list.html介面進行渲染:

tag:在頁面通過include匯入

django高階(四)分頁

paginator中提供了一些類來實現資料管理分頁,這些類存在於django core paginator.py paginator物件,對所有的資料進行分頁,該物件有乙個方法page num 返回某一頁,生成乙個page物件。paginator 列表,int 返回分頁物件,引數為列表資料,每面資料...

django 分頁功能

django 分頁功能 django自帶了paginator,功能有一定侷限,使用django pure pagination功能更為強大 github傳送門 1 使用pip源安裝 pip install django pure pagination pure pagination 3 在setti...

Django 內建分頁

from django.core.paginator import paginator,page userlist models.user.objects.all paginator paginator userlist,10 per page 每頁顯示條目數量 count 資料總個數 num pa...