【问题标题】:Loop over range in Django Html Template在 Django Html 模板中循环范围
【发布时间】:2020-11-27 18:21:33
【问题描述】:

在我的 django 模板中,我想按如下数量复制一行:

类似于重复材料请求 67 14 次,34 15 次等等

为此,我在如下列表中检索了数量:

d_docket = AllotmentDocket.objects.filter(parent_company = client_pk.pk, transaction_date__range =[start, end]).order_by('-transaction_date')

quan = list(d_docket.values_list('product1_quantity', flat=True))

给出:

[14, 15, 15, 15, 15, 20, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 14, 15, 13, 6, 15, 15, 10、15、15、15、7、8]

但是如何在 django 模板中遍历quan 的每个元素的范围?

当前模板:

{% for i in query %}
        <tr>


            <td class="align-middle">{{ i.sales_order.owner }}</td>
            <td class="align-middle">{{ i.sales_order.pk }}</td>
            <td class="align-middle">{{ i.sales_order.flow }}</td>
            <td class="align-middle">{{ i.sales_order.kit }}</td>
        </tr>

{% endfor %}

【问题讨论】:

    标签: python html django django-templates


    【解决方案1】:

    将您的queryquan 作为上下文。然后,在当前 forloop 的每次迭代中使用 quan[forloop.counter0],如下所示:

    {% for i in query %}
        {% with index=forloop.counter0 %}
        {% with ''|center:quan.index as range %}
        {% for _ in range %}
            <tr>
              <td class="align-middle">{{ i.sales_order.owner }}</td>
              <td class="align-middle">{{ i.sales_order.pk }}</td>
              <td class="align-middle">{{ i.sales_order.flow }}</td>
              <td class="align-middle">{{ i.sales_order.kit }}</td>
            </tr>
        {% endfor %}
        {% endwith %}
        {% endwith %}
    {% endfor %}
    

    【讨论】:

    • 我出现这个错误:无法解析余数:'(forloop.counter0)' from '''|center:quan.(forloop.counter0)'
    • 第 102 行的块标记无效:'endwith',预期为 'empty' 或 'endfor'。您是否忘记注册或加载此标签?我正在使用正确的`{% endwith %}`
    • @RahulSharma 你能试试新的编辑吗?我们会尽最大努力一起找到它;p
    • 新的编辑给'with' received an invalid token: "''|center:quan.index"
    • @RahulSharma 我想我现在明白了。我之前的解决方案是正确的,但我忘记了%。你可以用编辑后的答案再试一次吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 2015-02-05
    • 2021-12-26
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    相关资源
    最近更新 更多