Django 分页功能

Django 分页功能比较强大,这边是结合官网的内容写的可以参考

https://docs.djangoproject.com/en/1.9/topics/pagination/


>>>  from  django.core.paginator  import  Paginator
>>> objects  =  [ 'john' 'paul' 'george' 'ringo' ]
>>> p  =  Paginator(objects,  2 )
 
>>> p.count
4
>>> p.num_pages
2
>>>  type (p.page_range)   # `<type 'rangeiterator'>` in Python 2.
< class  'range_iterator' >
>>> p.page_range
range ( 1 3 )
 
>>> page1  =  p.page( 1 )
>>> page1
<Page  1  of  2 >
>>> page1.object_list
[ 'john' 'paul' ]
 
>>> page2  =  p.page( 2 )
>>> page2.object_list
[ 'george' 'ringo' ]
>>> page2.has_next()
False
>>> page2.has_previous()
True
>>> page2.has_other_pages()
True
>>> page2.next_page_number()
Traceback (most recent call last):
...
EmptyPage: That page contains no results
>>> page2.previous_page_number()
1
>>> page2.start_index()  # The 1-based index of the first item on this page
3
>>> page2.end_index()  # The 1-based index of the last item on this page
4
 
>>> p.page( 0 )
Traceback (most recent call last):
...
EmptyPage: That page number  is  less than  1
>>> p.page( 3 )
Traceback (most recent call last):
...
EmptyPage: That page contains no results

 

views

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from  django.core.paginator  import  Paginator, EmptyPage, PageNotAnInteger
from  django.shortcuts  import  render
 
def  listing(request):
     contact_list  =  Contacts.objects. all ()
     paginator  =  Paginator(contact_list,  25 # Show 25 contacts per page
 
     page  =  request.GET.get( 'page' )
     try :
         contacts  =  paginator.page(page)
     except  PageNotAnInteger:
         # If page is not an integer, deliver first page.
         contacts  =  paginator.page( 1 )
     except  EmptyPage:
         # If page is out of range (e.g. 9999), deliver last page of results.
         contacts  =  paginator.page(paginator.num_pages)
 
     return  render(request,  'list.html' , { 'contacts' : contacts})

  

网页html 代码编写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{% for contact in contacts %}
     {# Each "contact" is a Contact model object. #}
     {{ contact.full_name|upper }}< br  />
     ...
{% endfor %}
 
< div  class="pagination">
     < span  class="step-links">
         {% if contacts.has_previous %}
             < a  href="?page={{ contacts.previous_page_number }}">previous</ a >
         {% endif %}
 
         < span  class="current">
             Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}.
         </ span >
 
         {% if contacts.has_next %}
             < a  href="?page={{ contacts.next_page_number }}">next</ a >
         {% endif %}
     </ span >
</ div >

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值