Django中的分页(显示前2页,后2页和本页)

2016年07月07日 原创
关键词: django 模板
摘要 在Django中通过自定义filter实现好用的分页。
  1. 创建一个名为templatetags的python module。
  2. 创建pagination_tool.py
    from django import template
    register = template.Library()
    @register.filter
    def range_pagination_5(curr,end):
        if curr==end:
            if end <= 5:
                result=[i+1 for i in range(end)]
            else:
                result=[curr-4+i for i in range(5)]
                if result.__len__()==0:
                    result=[i+1 for i in range(curr)]
        elif curr==1:
            if end > 5:
                result=[curr+i for i in range(5)]
            else:
                result=[curr+i for i in range(end)]
        elif curr==end-1:
            if end <= 5:
                result=[i+1 for i in range(end)]
            else:
                result = [curr - 3 + i for i in range(4)]
                if result==[]:
                    result = [i + 1 for i in range(end)]
                else:
                    result.append(end)
        elif curr==2:
            result=[curr+i for i in range(4)]
            result.insert(0,1)
        else:
            result=[curr-2,curr-1,curr,curr+1,curr+2]
        return result
    

     

  3. 在模板页面引入该过滤器。{% load pagination_tool %}
  4. 使用
    <nav class="text-center">
         <ul class="pagination">
             <li>
                 <a href="{% url 'books' %}?page=1" aria-label="Previous"> <span aria-hidden="true">首页</span> </a>
             </li>
        {% for n in  books.number|range_pagination_5: books.paginator.num_pages %}
              <li
              {% if n ==  books .number %}
                   class="active"
               {% endif %}
                          >
            <a href="{% url ' books ' %}">{{n}}</a>
            </li>
         {% endfor %}
            <li>
          <a href="{% url ' books ' %}?page={{ books.paginator.num_pages}}"> <span aria-hidden="true">尾页</span> </a>
            </li>
         </ul>
     </nav>