django - 如何使用 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
解决方案
您可以使用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'))
)
推荐阅读
- c++ - 从标准数组中擦除元素
- for-loop - 如何将 for 循环转换为数学函数/表达式?
- python - 如何一次在 RAM 中保存包含数百万个字典的 python 列表?
- java - Spring security OAuth2: permitAll() 对我不起作用(HTTP 401 for unprotected endpoints)
- java - 将包含子目录和 java 文件的 2 个顶级目录编译成 java jar 文件 UNIX
- oracle - 在 Oracle 中将小时数添加到时间数据类型
- java - 如何复制一个对象(在这种情况下是一个数组列表)然后只清除其中一个
- java - 在 Selenium 中,使用 CRTL + Shift + N 以隐身模式启动浏览器在 Sauce Labs 中不起作用
- powershell - 将文件内容与 Powershell 中的字符串进行比较
- java - 在 Google Data Flow 上的 Spring Boot 项目中运行 Apache Beam 管道