import models
from django.views.generic import ListView
class CarListView(ListView):
model = models.Car # shorthand for setting queryset = models.Car.objects.all()
template_name = 'app/car_list.html' # optional (the default is app_name/modelNameInLowerCase_list.html; which will look into your templates folder for that path and file)
context_object_name = "car_list" #default is object_list as well as model's_verbose_name_list and/or model's_verbose_name_plural_list, if defined in the model's inner Meta class
paginate_by = 10 #and that's it !!
{% for foo,name in data %}
<div class="col-md-3 table-responsive">
{% for k,v in foo %}
<tr>
<th>{{ forloop.counter }}</th>
<td>{{ k }}</td>
<td>{{ v }}</td>
</tr>
{% endfor %}
{% include 'pagination.html' with pname=name page_obj=foo %}
</div>
{% endfor %}
3 回答
假设,我在app / models.py中有一个名为
FileExam(models.Model)
的类:app/models.py
app/views.py
get_context_data
只有一点变化,并添加了来自django文档的分页代码hereapp/templates/app/exam_list.html
normal content list
paginate section
app/urls.py
我想你要求提供有关使用新的基于类的视图分页的信息,因为使用传统的基于函数的视图,它很容易找到 . 我发现只需设置
paginate_by
变量即可激活分页 . 见Class-based generic views .例如,在
views.py
中:在您的模板(
car_list.html
)中,您可以包含这样的分页部分(我们有一些可用的上下文变量:is_paginated
,page_obj
和paginator
) .要显示的页面由GET参数指示,只需将
?page=n
添加到URL即可 .我们有两种方法可以做到这一点 .
第一个很简单,只需设置类字段
paginate_by
. 我们不需要使用get_context_data
方法 .第二种方法有点复杂但我们可以更好地理解分页并定制复杂的分页或几个分页 . 让我们来看看它 .
它可以分三步完成 .
1.覆盖View的get_context_data方法 .
传递
page_keys
和pages
,以便我们可以迭代列表并避免硬编码 .2.自定义子模板 .
我们定义了一些变量,因此我们可以遍历分页列表 .
pagination.html
3.自定义外部模板 .
index.html