在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来分页显示数据了。