如何将view.py的int传递给{Django模板的for循环}?

2024-09-29 23:24:46 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我想在切片中传递的模板的代码

<div class="swiper-container swiper-container2">
  <div class="swiper-wrapper">
  {% for category in smartphone_banners %}
    {% for product in category.product_detail_set.reverse|slice:"1:3:-1" %}
    <div class="swiper-slide py-2">
      <a href="product/{{product.name}}/{{product.id}}" style="text-decoration: none;">
        <img src="{{product.imageURL}}" alt="" style="width: 80%; margin: 0 auto;">  
        <h6 class="mt-1">{{product.name}}</h6>
        <p>{{product.price}}</p>
      </a>
    </div>
    {% endfor %}
  {% endfor %}
  </div>
</div>

我想用以下内容替换slice:"1:3:-1" %}slice:"1:totalnu:-1" %}slice:"1:{{totalnu}}:-1" %}, 但这两种方法都不起作用

如何传递totalnu的值?这是我在views.py中的代码:

        for i in smartphone_banners: 
        for pr in i.product_detail_set.reverse()[1:3:-1]:
            print(pr)
            print(totalnu)
            totalnu = totalnu + 1 
    print(totalnu)
    lists = []
    for ifn in smartphone_banners:
        for prf in ifn.product_detail_set.reverse()[(totalnu - 2):totalnu:-1]:
            print( 'this is the fonal.', prf)

Tags: 代码indivforsliceproductclassreverse
1条回答
网友
1楼 · 发布于 2024-09-29 23:24:46

使用给定的一组变量(上下文)调用模板对象的render()方法。
上下文类似于字典。
创建包含变量的上下文,包括来自views.py的totalnu

context = { 'totalnu': totalnu }

你应该把这个render(request, template, context)放在你的views.py
在模板中,使用{{ totalnu }}传递totalnu的值

相关问题 更多 >

    热门问题