Django之分页功能-转
原文地址:https://www.cnblogs.com/kongzhagen/p/6640975.html
注意事项:
在django中,注册自定义 pagetag.py
from django import template register = template.Library() @register.filter def kong_upper(val): print ('val from template:',val) return val.upper() from django.utils.html import format_html @register.simple_tag def circle_page(curr_page,loop_page): offset = abs(curr_page - loop_page) if offset < 3: if curr_page == loop_page: page_ele = '<li class="active"><a href="?page=%s">%s</a></li>'%(loop_page,loop_page) else: page_ele = '<li><a href="?page=%s">%s</a></li>'%(loop_page,loop_page) return format_html(page_ele) else: return ''
新增内容:
news/views.py
from django.shortcuts import render,redirect from wagtail.wagtailcore.models import Page, Orderable #wagtail usered from news.models import NewsPage from django.core.urlresolvers import resolve from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger def NewSplitPage(request): newspages = NewsPage.objects.all() paginator = Paginator(newspages,3,2) #每页3条数据,少于2条,合并上页 page = request.GET.get('page') try: post = paginator.page(page) except PageNotAnInteger: post = paginator.page(1) except EmptyPage: post = paginator.page(paginator.num_pages) return render(request,'news/news_index_page.html',{"newspages":post})
修改 news_index_page.html 插入以下代码(实现分页)
<nav aria-label="Page navigation"> <ul class="pagination"> {% if newspages.has_previous %} <li> <a href="?page={{ newspages.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true">«</span> </a> </li> {% endif %} {% for pg in newspages.paginator.page_range %} {% circle_page newspages.number pg %} {% endfor %} {% if newspages.has_next %} <li> <a href="?page={{ newspages.next_page_number }}" aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> {% endif %} </ul> </nav>
修改urls.py ,增加:
from news import views as nw_views
...
url(r'^NewSplitPage/$', nw_views.NewSplitPage, name='NewSplitPage'),