【问题标题】:django foorloop counter restarts in a new pagedjango forloop 计数器在新页面中重新启动
【发布时间】:2021-12-02 06:34:24
【问题描述】:

目前我正在用 django 编写一个简单的 todolist。我有一个用于显示项目列表的视图和 html 文件,并且我想要从 1 开始的表中每个任务的编号。我在模板中使用{% footloop.counter %}

在我编写分页器之前一切都很好。当您选择转到下一页时,计数器再次从 1 开始,因此每页表格中的数字也从 1 开始。但我希望这些数字按顺序继续到最后一页。是否有任何模板标签或代码sn-ps? 提前致谢。

这里是涉及的代码:

**list.html:**

    {% for task in tasks %}
                            <tbody>
                            <tr>
                                <th scope="row" class="col-md-1">{{ forloop.counter }}</th>
                                <td class="col-md-2">{{ task.title }}</td>
                                <td class="col-md-3">{{ task.description|truncatewords:10 }}</td>
                                <td class="col-md-2">{{ task.time|date:"H:i" }} - {{ task.time|date:"D d M , Y" }}</td>
                            </tr>
                            </tbody>
    {% endfor %}



<!--Pagination-->

 {% if is_paginated %}
        <div class="container p-4">
            <div class="pagination justify-content-center">
                <span class="step-links">
                    {% if page_obj.has_previous %}
                        <a href="{% url 'home:list' 1 %}">&laquo; first</a>
                        <a href="{% url 'home:list' page_obj.previous_page_number %}">previous</a>
                    {% endif %}

                    <span class="current">
                        Page {{ page_obj.number }} of {{page_obj.paginator.num_pages }}
                    </span>

                    {% if page_obj.has_next %}
                        <a href="{% url 'home:list' page_obj.next_page_number %}">next</a>
                        <a href="{% url 'home:list' page_obj.paginator.num_pages%}">last &raquo;</a>
                    {% endif %}
                </span>
            </div>
        </div>
    {% endif %} 

【问题讨论】:

    标签: python django pagination templatetags


    【解决方案1】:

    您可以尝试构建自己的模板标签并在模板上使用它,如下所示:-

    @register.filter
    def adjust_for_counter(value, page):
        value, page = int(value), int(page)
        counter_value = value + ((page - 1) * settings.RESULTS_PER_PAGE)
        return counter_value
    

    并在 html 中像下面这样调用它:-

    {{ forloop.counter|adjust_for_pagination:page }}
    

    更多详情可以参考以下链接:- https://djangosnippets.org/snippets/1391/

    【讨论】:

    • 非常感谢您的回答。这个标签立即解决了我的问题(在您发送的链接中评论):{{ page_obj.start_index|add:forloop.counter0 }}
    猜你喜欢
    • 2016-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    • 2011-03-25
    相关资源
    最近更新 更多