newpaginator
'''
http://my.oschina.net/kelvinfang/blog/134342
'''
from django.core.paginator import Paginator
class NewPaginator(Paginator):
def __init__(self, object_list, per_page, range_num=2, orphans=0, allow_empty_first_page=True):
Paginator.__init__(self, object_list, per_page, orphans, allow_empty_first_page)
self.range_num = range_num
def page(self, number):
self.page_num = number
return super(NewPaginator, self).page(number)
def _page_range_ext(self):
num_count = 2 * self.range_num + 1
if self.num_pages <= num_count:
return range(1, self.num_pages + 1)
num_list = []
num_list.append(self.page_num)
for i in range(1, self.range_num + 1):
if self.page_num - i <= 0:
num_list.append(num_count + self.page_num - i)
else:
num_list.append(self.page_num - i)
if self.page_num + i <= self.num_pages:
num_list.append(self.page_num + i)
else:
num_list.append(self.page_num + i - num_count)
num_list.sort()
return num_list
page_range_ext = property(_page_range_ext)
view
#from django.core.paginator import Paginator
import newpaginator
class IndexView(View):
def get(self, request, *args, **kwargs):
。。。
paginator = newpaginator.NewPaginator(servers, 2)
try:
page = int(request.GET.get('page','1'))
except ValueError:
page = 1
try:
servers = paginator.page(page)
except :
servers = paginator.page(paginator.num_pages)
return render(request, "instances/index.html", {"servers":servers,'page':page,'paginator':paginator})
template
<ul class="pagination">
{% if servers.has_previous %}
<li><a href="?page={{ servers.previous_page_number }}" class="prev"><<</a></li>
{% else %}
<li class="disabled"><a href="#"><<</a></li>
{% endif %}
{% for page in servers.paginator.page_range_ext %}
{% if page %}
{% ifequal page servers.number %}
<li class="active"><a href="#">{{ page }}</a></li>
{% else %}
<li><a href="?page={{ page }}" class="page">{{ page }}</a></li>
{% endifequal %}
{% else %}
...
{% endif %}
{% endfor %}
{% if servers.has_next %}
<li><a href="?page={{ servers.next_page_number }}" class="next">>></a></li>
{% else %}
<li class="disabled"><a href="#">>></a></li>
{% endif %}
</ul>
参考
django分页技术django-pagination和Paginator(基础篇)
Django中扩展Paginator实现分页
-eof-