首页 > 代码库 > Django 分页功能
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.count4>>> p.num_pages2>>> type(p.page_range) # `<type ‘rangeiterator‘>` in Python 2.<class ‘range_iterator‘>>>> p.page_rangerange(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 page3>>> page2.end_index() # The 1-based index of the last item on this page4>>> 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
from django.core.paginator import Paginator, EmptyPage, PageNotAnIntegerfrom django.shortcuts import renderdef 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 代码编写
{% 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="http://www.mamicode.com/?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="http://www.mamicode.com/?page={{ contacts.next_page_number }}">next</a> {% endif %} </span></div>
Django 分页功能
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。