在Django中,可以使用Django自帶的Paginator來實現分頁顯示數據。以下是一個簡單的示例代碼:
from django.core.paginator import Paginator, Page
from .models import YourModel
def your_view(request):
data = YourModel.objects.all()
paginator = Paginator(data, 10) # 每頁顯示10條數據
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return render(request, 'your_template.html', {'page_obj': page_obj})
{% for item in page_obj %}
<!-- 顯示item的內容 -->
{% endfor %}
<!-- 顯示分頁鏈接 -->
<div class="pagination">
<span class="step-links">
{% if page_obj.has_previous %}
<a href="?page=1">« first</a>
<a href="?page={{ page_obj.previous_page_number }}">previous</a>
{% endif %}
<span class="current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
<a href="?page={{ page_obj.next_page_number }}">next</a>
<a href="?page={{ page_obj.paginator.num_pages }}">last »</a>
{% endif %}
</span>
</div>
通過以上步驟,就可以實現在Django中使用Paginator來分頁顯示數據了。