分頁(yè)示例:
在views.py中:
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
def ProductList(request):
data = getData()
winery = models.Winery.objects.all().order_by("-id") # 以id倒序
paginator = Paginator(winery, 3) # 3個(gè)為一頁(yè)
page = request.GET.get('page')
try:
wine = paginator.page(page)
except PageNotAnInteger: # page不是integer
wine = paginator.page(1)
except EmptyPage: # 如果傳遞的page不在我們的分頁(yè)范圍中
wine = paginator.page(paginator.num_pages)
data["winery"] = wine
return render(request, 'productlist.html', {'data':data})
# 在模板中
<div class="pagination ">
<span class="step-links">
{% if data.winery.has_previous %}
<a href="?page={{ data.winery.previous_page_number }}">上一頁(yè)</a>
{% endif %}
<span class="current ">
第{{ data.winery.number }}頁(yè)致板,共{{ data.winery.paginator.num_pages }}頁(yè)
</span>
{% if data.winery.has_next %}
<a href="?page={{ data.winery.next_page_number }}">下一頁(yè)</a>
{% endif %}
</span>
</div>
注意:我們一般是在settings.py
中設(shè)置分頁(yè)大小:
# 自定義
PRODUCT_PAGE_SIZE = 3
在views.py
中:
paginator = Paginator(winery, settings.PRODUCT_PAGE_SIZE) # 3個(gè)為一頁(yè)