分頁器(paginator)
批量匯入資料:
booklist=
for i in range(100):
book.objects.bulk_create(booklist)
''''''分頁器的使用:
book_list=book.objects.all()
paginator = paginator(book_list, 10)
print("count:",paginator.count) #資料總數
print("num_pages",paginator.num_pages) #總頁數
print("page_range",paginator.page_range) #頁碼的列表
page1=paginator.page(1) #第1頁的page物件
for i in page1: #遍歷第1頁的所有資料物件
print(i)
print(page1.object_list) #第1頁的所有資料
page2=paginator.page(2)
# 拋錯
#page=paginator.page(12) # error:emptypage
#page=paginator.page("z") # error:pagenotaninteger
'''book_list=book.objects.
all(
) paginator = paginator(book_list,10)
page = request.get.get(
'page',1
)#獲取當前選中的頁碼
currentpage=
int(page)
try:
(page)
book_list = paginator.page(page)
except pagenotaninteger:
book_list = paginator.page(1)
#頁數引數未知時限制為1
except emptypage:
book_list = paginator.page(paginator.num_pages)
#頁數超限顯示為最後一頁
return render(request,
"index.html"
,)index.html:
lang
="en"
>
>
charset
="utf-8"
>
>
titletitle
>
rel=
"stylesheet"
href
=""integrity
="sha384-bvyiisifek1dgmjrakycuhahrg32omucww7on3rydg4va+pmstsz/k68vbdejh4u"
crossorigin
="anonymous"
>
head
>
>
class
="container"
>
>
分頁器h4
>
>
>
} -----}li
>
ul>
class
="pagination"
id="pager"
>
class
="previous"
>
href
="/index/?page=}"
>
>
li>
class
="previous disabled"
>
href
="#"
>
>
li>
class
="item active"
>
href
="/index/?page=}"
>
}a>
li>
class
="item"
>
href
="/index/?page=}"
>
}a>
li>
class
="next"
>
href
="/index/?page=}"
>
>
li>
class
="next disabled"
>
href
="#"
>
>
li>
ul>
div>
body
>
html
>
擴充套件
def
index
(request)
: book_list=book.objects.
all(
) paginator = paginator(book_list,15)
page = request.get.get(
'page',1
) currentpage=
int(page)
# 如果頁數十分多時,換另外一種顯示方式
if paginator.num_pages>11:
if currentpage-
5<1:
pagerange=
range(1
,11)elif currentpage+
5>paginator.num_pages:
pagerange=
range
(currentpage-
5,paginator.num_pages+1)
else
: pagerange=
range
(currentpage-
5,currentpage+5)
else
: pagerange=paginator.page_range
try:print
(page)
book_list = paginator.page(page)
except pagenotaninteger:
book_list = paginator.page(1)
except emptypage:
book_list = paginator.page(paginator.num_pages)
return render(request,
"index.html"
,locals()
)
Django元件 分頁器
批量匯入資料 booklist for i in range 100 book.objects.bulk create booklist 分頁器的使用 book list book.objects.all paginator paginator book list,10 print count pa...
Django元件 分頁器
批量匯入資料 booklist for i in range 100 book.objects.bulk create booklist 分頁器的使用 book list book.objects.all paginator paginator book list,10 print count pa...
Django元件之 分頁器
django自帶分頁器 paginator 用起來非常方便。怕自己寫的出bug,可以使用現成的 批量匯入資料 booklist for i in range 100 book.objects.bulk create booklist 分頁器的使用 book list book.objects.all...