我已经成功地将分页添加到 list_contacts 视图(显然是用于 Contact 模型)。现在我正在尝试设置模板上下文,以便我可以将分页显示限制为如下所示:
< 1 ... 5 6 7 8 9 ... 42 >
我从这个答案出发并尝试使用“分页器”模板标签,但未成功。主要问题是我使用ListView
而不是 old 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()