Django-分页

2018-05-06  本文已影响0人  mo_陌上花开

Django-分页

1.创建对象

Paginator 对象的 page()方法返回 Page 对象,不需要手动构造

2.属性

object_list:当前页上所有对象的列表
number:当前页的序号,从 1 开始
paginator:当前 page 对象相关的 Paginator 对象

3.方法

has_next():如果有下一页返回 True
has_previous():如果有上一页返回 True
has_other_pages():如果有上一页或下一页返回 True
next_page_number():返回下一页的页码,如果下一页不存在,抛出 InvalidPage 异常
previous_page_number():返回上一页的页码,如果上一页不存在,抛出InvalidPage异常
len():返回当前页面对象的个数
迭代页面对象:访问当前页面中的每个对象

4.示例

views
def view_post(request,pIndex):
    # try:
    uadmin = request.session['uadmin']
    authorid = adminid.objects.get(admin = uadmin)
    authorlist = post.objects.filter(author = authorid)
    p = Paginator(authorlist, 1)
    print(authorlist)
    if pIndex == '':
        pIndex = int(pIndex)
    list = p.page(pIndex)
    plist = p.page_range
    # print('hobby', shrlist[0].shrname)
    # hero = HeroInfo.objects.get
    return render(request, 'invitation/view_post.html', {'request':request, 'authorlist': list,'plist':plist,'pIndex':pIndex})
    # except Exception as e:
    #   return redirect(reverse('login:login'))
html
<ul class="mr-list">
  {% for item in authorlist%}
  <li>标题:{{ item.title }}</li>
  <li>类型:{{ item.classify }}</li>
  <li>内容~~~</li>
  {%autoescape off%}
  <textarea style="resize:none;width:500px; height:210px ">{{ item.content }}</textarea>
   {%endautoescape%}
   <li>发帖时间:{{ item.posted_time }}<li>
   {% endfor %}
   {% if authorlist.has_previous %}
   <a href="/invitation/view_post/{{ authorlist.previous_page_number }}/">上一页&nbsp;&nbsp;</a>
   {% else %}
         上一页
   {% endif %}
   {% for pindex in plist %}
   {% if pindex == pIndex %}
        {{ pindex }}
   {% else %}
       <a href="/invitation/view_post/{{ pindex }}/">{{ pindex }}</a>&nbsp;&nbsp;
   {% endif %}
   {% endfor %}
   {% if authorlist.has_next %}
       <a href="/invitation/view_post/{{ authorlist.next_page_number }}/">下一页&nbsp;&nbsp;</a>
   {% else %}
        下一页
   {% endif %}
 </ul>
应用url

url(r'^view_post/(\d+)/$',views.view_post,name='view_post'),

上一篇 下一篇

猜你喜欢

热点阅读