视图函数Django中的分页器



我正试图在博客网站的帖子页面上添加分页选项。我想在呈现页面的视图函数上实现分页器,我从Django的文档中找到了这个例子,但它不起作用。有什么帮助吗?

查看功能:

def blog(request):
posts = Post.objects.all().order_by('-date_posted')
paginator = Paginator(posts, 2)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
context = {
'posts': posts,
'page_obj': page_obj,
'title': 'Blog',
'banner_page_title': 'Blog',
'page_location': 'Home / Blog'
}
return render(request, 'blog/blog.html', context)

html渲染

<nav class="blog-pagination justify-content-center d-flex">
<ul class="pagination">
{% if is_paginated %}
{% if page_obj.has_previous %}
<li class="page-item">
<a href="?page={{ page_obj.previous_page_number }}" class="page-link" aria-label="Previous">
<span aria-hidden="true">
<span class="ti-arrow-left"></span>
</span>
</a>
</li>
{% endif %}
{% for num in page_obj.paginator.page_range %}
{% if page_obj.number == num %}
<li class="page-item active">
<a href="?page={{ num }}" class="page-link">{{ num }}</a>
</li>
{% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
<li class="page-item">
<a href="?page={{ num }}" class="page-link">{{ num }}</a>
</li>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<li class="page-item">
<a href="?page={{ page_obj.next_page_number }}" class="page-link" aria-label="Next">
<span aria-hidden="true">
<span class="ti-arrow-right"></span>
</span>
</a>
</li>
{% endif %}
{% endif %}
</ul>
</nav>

url路由

path('blog/', blog, name='blog'),

删除{% if is_paginated %},因为它没有返回任何值,这就是为什么你看不到任何数字(如果{% endif %},不要忘记删除更接近的数字(

您可以从page_obj访问分页对象

{% for post in page_obj %}
{{ post }}
{% endfor %}

这是经过修改的HTML

{% for post in page_obj %}
{{ post.text }}<br>
{% endfor %}

<nav class="blog-pagination justify-content-center d-flex">
<ul class="pagination">
{% if page_obj.has_previous %}
<li class="page-item">
<a href="?page={{ page_obj.previous_page_number }}" class="page-link" aria-label="Previous">
<span aria-hidden="true">
<span class="ti-arrow-left"></span>
</span>
</a>
</li>
{% endif %}
{% for num in page_obj.paginator.page_range %}
{% if page_obj.number == num %}
<li class="page-item active">
<a href="?page={{ num }}" class="page-link">{{ num }}</a>
</li>
{% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
<li class="page-item">
<a href="?page={{ num }}" class="page-link">{{ num }}</a>
</li>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<li class="page-item">
<a href="?page={{ page_obj.next_page_number }}" class="page-link" aria-label="Next">
<span aria-hidden="true">
<span class="ti-arrow-right"></span>
</span>
</a>
</li>
{% endif %}
</ul>
</nav>

最新更新