Django撸博客之添加分页功能

认识分页对象

django内置了一个Paginator对象,能将给定的list分成指定的数量分页.
贴上官方文档的翻译: 翻译分页 / 原文

有两个对象需要明确:
Paginator: 分页对象,用于管理页面
Page: 页面对象,用于代表某一页

先在视图中引入:

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

class PostListView(TagView):
    template_name = 'blog/post/list.html'
    paginator_by = 2  # 每页分多少
    page = 1  # 默认页

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        posts = Post.objects.filter(status='1')  # 获取对象列表
        paginator = Paginator(posts, self.paginator_by)  # 创建分页对象

        try:
            page_obj = paginator.page(self.page)  # 获取某页面对象
        except EmptyPage:
            page_obj = paginator.page(paginator.num_pages)
        except PageNotAnInteger:
            page_obj = paginator.page(1)

        context['page'] = page_obj  # 设置用于渲染的上下文
        return context

    def get(self, request, *args, **kwargs):
        self.page = request.GET.get('page')  # 获取并设置页码
        return super().get(request, *args, **kwargs)

这样,就反回了一个Page对象, 并且在前端可以使用了


<div >
    {% for post in page.object_list %}
        {{ post }}  
    {% endfor %}
div>


<ul class="am-pagination am-pagination-centered">
    
    {% if page.has_previous %}
        <li class=""><a href="?page={{ page.previous_page_number }}">«a>li>
    {% endif %}

    
    {% for num in page.paginator.page_range %}
        <li class="{% if num == page.number %}am-disabled{% endif %}"><a href="?page={{ num  }}">{{ num }}a>li>
    {% endfor %}

    
    {% if page.has_next%} 
        <li ><a href="?page={{ page.next_page_number }}">»a>li>
    {% endif %}
ul>

你可能感兴趣的:(Django撸博客系)