美文网首页python之路
django笔记(七)分页组件

django笔记(七)分页组件

作者: 非鱼2018 | 来源:发表于2021-02-27 11:14 被阅读0次

    效果:


    image.png

    视图文件

    from django.core.paginator import Paginator
    
    def titles(request):
        titles = Titles.objects.order_by('create_date')  #获得模型数据
       #获得pagesize,默认为5
        page_size=int(request.GET.get('page_size')) if request.GET.get('page_size') else 5
        paginator = Paginator(titles, page_size)
        page = request.GET.get('page')  #获得第几页
        titles = paginator.get_page(page)  #获得第几页的数据
        print(type(titles))
        for  title in titles.paginator.page_range:
            print(title)  #页码范围
       print(titles.number)  #当前页码
        context = {'titles': titles}
        return render(request, 'myapp/titles.html', context)
    
    

    模板文件

    <nav aria-label="Page navigation">
        <ul class="pagination">
            
            {% if titles.has_previous %}
            <li class="page-item">    <a class="page-link" href="?page={{ titles.previous_page_number }}">previous</a></li>
            {% endif %}
    
    {% for title in titles.paginator.page_range %}
            {% ifequal title titles.number %}
    <li class="page-item">  <a class="page-link" style="height:50px" href="?page={{ title }}">{{ title}}</a></li>
    {% else %} #请求的页码数等于当前页则高度为50px,突出显示当前页
          <li class="page-item">       <a class="page-link" href="?page={{ title }}">{{ title}}</a></li>{% endifequal %}
    {% endfor %}
    
            {% if titles.has_next %}
               <li class="page-item">    <a class="page-link" href="?page={{ titles.next_page_number }}">Next</a></li>
            {% endif %}
    
        </ul>
    </nav>
    
    共{{titles.paginator.count}}条数据,显示第{{titles.start_index}}~{{titles.end_index}}条数据,每页显示{{titles.paginator.per_page}}
    
    
    <form action="{% url 'myapp:titles'%}"  method="get">
            {% csrf_token %}
          <select name="page_size">
              <option>5</option>
              <option>10</option>
              <option>15</option>
          </select>
          <button type="submit" class="btn btn-primary">重置</button>
        </form>
    {% endblock page_content %}
    

    相关文章

      网友评论

        本文标题:django笔记(七)分页组件

        本文链接:https://www.haomeiwen.com/subject/ztzxtltx.html