【问题标题】:Pagination: how to set the number of pages?分页:如何设置页数?
【发布时间】:2019-07-11 09:13:18
【问题描述】:

我有一个显示新闻列表的视图:

def index(request, page_number=1):
    news_list = get_list_or_404(NewsItem.objects.order_by('-pub_date'))
    news_paginator = Paginator(news_list, 10)
    return render(request, 'news/index.html', {'news_list': news_paginator.page(page_number))

如您所见,每页显示十条新闻。

模板:

<div class="paginator">
  <ul>
    <!-- Left arrow -->
      {% if news_list.has_previous %}
        <li class="arrow"><a class="no_underline" href="{% url 'news:index' news_list.previous_page_number %}"><b>&larr;</b></a></li>
      {% else %}
        <li class="arrow unavailable"><b>&larr;</b></li>
      {% endif %}

    <!-- Page numbers -->
      {% for page in news_list.paginator.page_range %}
         {% if page == news_list.number  %}
           <li class="current"><a class="no_underline" href="{% url 'news:index' page %}">{{ page }}</a></li>
         {% else %}
           <li><a class="no_underline" href="{% url 'news:index' page %}">{{ page }}</a></li>
         {% endif %}
      {% endfor %}

     <!-- Right arrow -->
       {% if news_list.has_next %}
         <li class="arrow"><a class="no_underline" href="{% url 'news:index' news_list.next_page_number %}"><b>&rarr;</b></a></li>
       {% else %}
         <li class="arrow unavailable"><b>&rarr;</b></li>
       {% endif %}
  </ul>
</div>

看起来像这样:

← 1 2 3 4 5 6 7 8 →

假设有 217 条新闻,我不希望列表底部有 21 个页码。相反,我更愿意设置限制:只有 5 个页码。但是这个限制必须稳定,无论页面列表中的当前位置,总是应该有 5 个页码:

← 1 2 3 4 5 →

← 11 12 13 14 15 →(在列表中间

← 17 18 19 20 21 →(显示最后一页

我怎样才能做到这一点?

【问题讨论】:

标签: django django-pagination


【解决方案1】:

你可以尝试在你的views.py中添加这个:

class Counter:
    count = 0

    def increment(self):
        self.count += 1
        return ''

然后添加到:

context = {'news_list': news_paginator.page(page_number),'Counter':Counter}
return render(request, 'news/index.html', context)

然后在你的html页面上:

  {% for page in news_list.paginator.page_range %}
     {% if page == news_list.number  %}  

     {% if Counter.count < 6 %}
     {{ Counter.increment }} 
       <li class="current"><a class="no_underline" href="{% url 'news:index' page %}">{{ page }}</a></li>
     {% endif %}

     {% else %}
       <li><a class="no_underline" href="{% url 'news:index' page %}">{{ page }}</a></li>
     {% endif %}
  {% endfor %}

【讨论】:

  • 不幸的是,它似乎不起作用。我完全按照你的建议做了,但是列表没有拆分,当前页面被隐藏了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-11
  • 2017-09-16
  • 1970-01-01
  • 2012-05-19
  • 2015-11-27
  • 1970-01-01
  • 2016-03-02
相关资源
最近更新 更多