How can we implement pagination to display data in Django?
In Django, you can utilize the built-in Paginator to implement pagination for displaying data. Below is a simple example code:
- Firstly, import the Paginator and Page classes.
from django.core.paginator import Paginator, Page
- Firstly, in the view function, query the data that needs to be displayed.
from .models import YourModel
def your_view(request):
data = YourModel.objects.all()
- Create a Paginator object and specify the number of items to display per page.
paginator = Paginator(data, 10) # 每页显示10条数据
- Get the current page number and based on it, retrieve the data for that page.
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
- Pass the paginated data to the template for rendering.
return render(request, 'your_template.html', {'page_obj': page_obj})
- Use the properties and methods of Paginator in the template to display paginated data.
{% 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>
By following the above steps, you can implement pagination for displaying data in Django using Paginator.