今天來講分頁功能
如果有很多比資料
不要一次顯示太多筆,一次只顯示10筆 用下一頁上一頁
https://docs.djangoproject.com/en/2.0/topics/pagination/
Paginator(<obj>, 10) 第二個餐數一次顯示10筆
store/views.py
...
def category(request):
categorys = Category.objects.all().order_by('id')
paginator = Paginator(categorys, 10)
page = request.GET.get('page')
categorys = paginator.get_page(page)
return render(request, 'store/category.html', {'categorys': categorys})
...
store/templates/store/category.html
...
<div class="pagination">
<span class="step-links">
{% if categorys.has_previous %}
<a href="?page=1">« first</a>
<a href="?page={{ categorys.previous_page_number }}">previous</a>
{% endif %}
<span class="current">
Page {{ categorys.number }} of {{ categorys.paginator.num_pages }}.
</span>
{% if categorys.has_next %}
<a href="?page={{ categorys.next_page_number }}">next</a>
<a href="?page={{ categorys.paginator.num_pages }}">last »</a>
{% endif %}
</span>
</div>
...
就完成了
如果要快速新增測試資料,可以跑forloop
for i in range(40):
Category.objects.create(name='test'+str(i))
示意圖
加點bootstrap 樣式吧
store/templates/store/category.html
<ul class="pagination">
{% if categorys.has_previous %}
<li class="page-item">
<a class="page-link" href="?page=1">« first</a>
</li>
<li class="page-item">
<a class="page-link" href="?page={{ categorys.previous_page_number }}">previous</a>
</li>
{% endif %}
{% for i in categorys.paginator.page_range %}
<li class="page-item {% if i == categorys.number %} active{% endif %}">
<a class="page-link" href="?page={{ i }}">{{ i }}</a>
</li>
{% endfor %}
{% if categorys.has_next %}
<li class="page-item">
<a class="page-link" href="?page={{ categorys.next_page_number }}">next</a>
</li>
<li class="page-item">
<a class="page-link" href="?page={{ categorys.paginator.num_pages }}">last »</a>
</li>
{% endif %}
</ul>
示意圖
樣式就完成了