def query(request):
"""
current_page:目前頁碼,預設第一頁
line_num:每頁顯示的行數,預設10行
table_line_count:總行數
page_count:總頁數
display_page_num_count:顯示的頁數位标簽總個數,預設10個
"""
current_page = int(request.GET.get('p',1))
line_num = int(request.COOKIES.get("per_page_line_num",10))
table_line_count=tablename.objects.count() ####統計表總行數,tablename指資料庫中的表,根據實際修改
display_page_num_count=10
####求總頁數
a,b=divmod(table_line_count,line_num) ####求除數和餘數,例如divmod(5,1)=(1,1)
if b>0:
page_count=a+1
else:
page_count = a
"""
first_page:首頁
last_page:尾頁
prev_page:上一頁
next_page:下一頁
first_display_page_num:第一個顯示的頁碼
last_display_page_num:最後一個顯示的頁碼
"""
first_page = "%s" % (1, "首頁")
last_page = "%s" % (page_count, "尾頁")
if current_page-1==0:
prev_page="%s" % (current_page, "上一頁")
else:
prev_page="%s" % (current_page-1, "上一頁")
if current_page==page_count:
next_page="%s" % (current_page, "下一頁")
else:
next_page="%s" % (current_page+1, "下一頁")
page_str=""
page_str+=first_page
page_str+=prev_page
if page_count<=display_page_num_count:
first_display_page_num = 1
last_display_page_num = page_count + 1
else:
# 總頁數大于10頁(隻顯示10個頁數标簽)
# 如果目前頁數《=5
# 顯示1-10頁數标簽
# 如果目前頁數x》5
# 顯示 x-4到x+5頁數标簽
# 如果目前頁數x》總頁數-5
# 顯示 總頁數-9 到總頁數之間的标簽
if current_page_num<=5:
first_display_page_num=1
last_display_page_num=display_page_num_count
elif 5
first_display_page_num=current_page_num-5+1
last_display_page_num=current_page_num+5
else:
first_display_page_num=page_count-5-5+1
last_display_page_num=page_count
for i in range(first_display_page_num, last_display_page_num):
if i == current_page:
page_str += "%s" % (i, i)
else:
page_str += "%s" % (i, i)
page_str += next_page
page_str += last_page
page_str = mark_safe(page_str)
response = render(request, 'query.html', locals())
response.set_cookie("per_page_line_num",line_num,path='/query/') ####設定每頁顯示的行數
return response