我已经成功地将分页添加到list_contacts视图中(显然对于Contact模型)。我现在正在尝试设置模板上下文,以便我可以将分页显示限制为:
< 1 ... 5 6 7 8 9 ... 42 >
我从this answer开始尝试使用“paginator”模板标记,但未成功。主要问题是我使用的是ListView
而不是旧的object_list
,而这两个不会以相同的方式设置上下文。
以下是我的观点:
from django.views.generic import ListView
from app.models import Contact
list_contacts = ListView.as_view(
model=Contact,
http_method_names = ['get'],
template_name='contacts.html',
context_object_name='contacts',
paginate_by=6
)
我的模板“contacts.html”:
<ul class="pagination">
{# Previous page link #}
{% if page_obj.has_previous %}
<li>
<a href="?page={{ page_obj.previous }}">«</a>
</li>
{% else %}
<li class="disabled">
<a href="#">«</a>
</li>
{% endif %}
{# First page #}
{% if show_first %}
<li>
<a href="?page=1">1</a>
</li>
<li>...</li>
{% endif %}
{# List of pages (with current "active") #}
{% for page in page_numbers %}
{% ifequal page page_obj.number %}
<li class="active">
<a href="#">{{ page }}</a>
</li>
{% else %}
<li>
<a href="?page={{ page }}">{{ page }}</a>
</li>
{% endifequal %}
{% endfor %}
{# Last page #}
{% if show_last %}
<li>...</li>
<li><a href="?page=last">{{ page_obj.pages }}</a></li>
{% endif %}
{# Next page link #}
{% if page_obj.has_next %}
<li>
<a href="?page={{ page_obj.next_page_number }}">»</a>
</li>
{% else %}
<li class="disabled">
<a href="#">»</a>
</li>
{% endif %}
</ul>
编辑:这是我的视图代码,最终正常工作
class ListContactsView(ListView):
model = Contact
http_method_names = ['get']
template_name = 'contacts.html'
context_object_name = 'contacts'
paginate_by = 6
def get_context_data(self, **kwargs):
_super = super(ListContactsView, self)
context = _super.get_context_data(**kwargs)
adjacent_pages = 2
page_number = context['page_obj'].number
num_pages = context['paginator'].num_pages
startPage = max(page_number - adjacent_pages, 1)
if startPage <= 3:
startPage = 1
endPage = page_number + adjacent_pages + 1
if endPage >= num_pages - 1:
endPage = num_pages + 1
page_numbers = [n for n in xrange(startPage, endPage) \
if n > 0 and n <= num_pages]
context.update({
'page_numbers': page_numbers,
'show_first': 1 not in page_numbers,
'show_last': num_pages not in page_numbers,
})
return context
list_contacts = ListContactsView.as_view()
答案 0 :(得分:1)
有不同的方法来实现这一目标(甚至是某些方法的组合):
get_context_data
PaginationMixin
第一个例子
class MyListView(ListView):
def get_context_data(self, **kwargs):
context = super(MyListView, self).get_context_data(**kwargs)
context['foo'] = 'bar'
return context