1
我已成功將分頁添加到list_contacts視圖(顯然是爲聯繫人模型)。而我現在想安裝模板背景下,這樣我可以限制分頁顯示,看起來像這樣:在ListView中切分頁?
< 1 ... 5 6 7 8 9 ... 42 >
我從this answer去,並試圖用「分頁程序」模板標籤,沒有成功。主要問題是我使用的是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()
的一個例子啊,我很愚蠢,我可以很輕鬆地做到這一點!謝謝:) –
只是一個問題,不應該那個方法簽名是get_context_data(self,** kwargs)? –
是的,它應該更新答案 –