首页 > 解决方案 > 如何使用 get_context_data 在基于类的视图中添加分页

问题描述

我想在我的列表视图中添加分页。我用过paginated_by=10,但它不起作用。请帮我在模板中的视图中添加分页。我应该在我的模板中放入什么 HTML

视图.py

class CompanyListView(LoginRequiredMixin, generic.TemplateView):
    template_name = 'superadmin/company/company.html'

    def get_context_data(self, **kwargs):   
        context = super(CompanyListView, self).get_context_data(**kwargs)
        context['companies'] = Company.objects.exclude(company_name='Apollo').exclude(company_is_deleted = True).annotate(number_of_company_users=Count('userprofile'))
        return context

标签: djangodjango-modelsdjango-formsdjango-templatesdjango-views

解决方案


您可以使用ListView而不是TemplateView. 这里是如何。

class CompanyListView(LoginRequiredMixin, generic.ListView):
    template_name = 'superadmin/company/company.html'
    queryset = Company.objects.all()
    context_object_name = 'companies'
    paginate_by = 10

    def get_queryset(self):
        return ( 
            self.queryset.exclude(company_name='Apollo')
            .exclude(company_is_deleted =True)
            .annotate(number_of_company_users=Count('userprofile'))
        )

推荐阅读