django 1.11通用视图自带分页功能

关于django分页在网上查了很多,也看了官方文档(1.8),不是很理解,于是看看源码,在通用视图中看到get_context_data(self,**kwargs)这个方法,原来通用视图中带的有分页功能

django/views/generic/list.py

class MultipleObjectMixin(ContextMixin):
    """
    A mixin for views manipulating multiple objects.
    """
    allow_empty = True
    queryset = None
    model = None
    paginate_by = None
    paginate_orphans = 0
    context_object_name = None
    paginator_class = Paginator
    page_kwarg = 'page'
    ordering = None
这个类是ListView的父类


django/views/generic/list.py

    def get_context_data(self, **kwargs):
        """
        Get the context for this view.
        """
        queryset = kwargs.pop('object_list', self.object_list)
        page_size = self.get_paginate_by(queryset)
        context_object_name = self.get_context_object_name(queryset)
        if page_size:
            paginator, page, queryset, is_paginated = self.paginate_queryset(queryset, page_size)
            context = {
                'paginator': paginator,
                'page_obj': page,
                'is_paginated': is_paginated,
                'object_list': queryset
            }
        else:
            context = {
                'paginator': None,
                'page_obj': None,
                'is_paginated': False,
                'object_list': queryset
            }
        if context_object_name is not None:
            context[context_object_name] = queryset
        context.update(kwargs)
        return super(MultipleObjectMixin, self).get_context_data(**context)
这个方法是ListView父类的一个方法


blog/views.py

class ArticlesView(ListView):
    template_name = 'blog/articles.html'
    context_object_name = 'articles_list'
    paginate_by = settings.PAGE_NUM #加上这句就自动开启了分页功能

    def get_queryset(self,):
        cid = self.kwargs.get('cid','')
        articles_list = Article.objects.filter(category=cid).order_by('-view_times').defer('text')
        return articles_list

    def get_context_data(self,**kwargs):
        return super(ArticlesView,self).get_context_data(**kwargs)

在模板中接收这几个参数就可以实现分页功能了
            context = {
                'paginator': paginator,         paginator对象
                'page_obj': page, 分页对象(第几页的对象)
                'is_paginated': is_paginated, 不知道这个是干嘛的
                'object_list': queryset                   模板变量


page_obj.has_previous				#是否有上一页
page_obj.has_next					#是否有下一页
page_obj.has_other_pages			#是否有上一页或下一页
page_obj.previous_page_number		#上一页页码数
page_obj.next_page_number			#下一页页码数
page_obj.start_index				#在(列表...)中的开始位置(limit中的位置[1:5])
page_obj.end_index					#在(列表...)中的结束位置
page_obj.paginator					#得到paginator对象
page_obj.number						#当前页码数

paginator.count						#数据总数
paginator.num_pages					#总页码数
paginator.page_range				#页码范围
{% for page in paginator.page_range %}


展开阅读全文
博主设置当前文章不允许评论。

没有更多推荐了,返回首页