简体   繁体   English

无法使用 for 循环呈现 django 模板中的值

[英]Cannot render values in django template using for loop

So i have a zipped list inside my view and I have passed it into context like this:所以我在我的视图中有一个压缩列表,我已经将它传递到这样的上下文中:

 combined_data = zip(hostnames_list, values, values1, values2, values3, values4, values5)

    context = {'combined_data': combined_data}

    

    return render(request, 'base/snmp-table.html', context)

but when i try to render this data into the django template like this, the data is not displayed:但是当我尝试将此数据渲染到 django 模板中时,数据未显示:

<table>
  <thead>
      <tr>
          <th>Hostname</th>
          <th>Value1</th>
          <th>Value2</th>
          <th>Value3</th>
          <th>Value4</th>
          <th>Value5</th>
          <th>Value6</th>
      </tr>
  </thead>
  <tbody>
  {% for host, val1, val2, val3, val4, val5, val6 in combined_data %}
      <tr>
          <td>{{host}}</td>
          <td>{{val1}}</td>
          <td>{{val2}}</td>
          <td>{{val3}}</td>
          <td>{{val4}}</td>
          <td>{{val5}}</td>
          <td>{{val6}}</td>
      </tr>
  {% endfor %}
  </tbody>
</table>

  
  </table>
  <script type="text/javascript">
    setTimeout(function () { 
      location.reload();
    }, 2 * 1000);
  </script>

The lists which are zipped are not empty because when i do this inside my view:压缩的列表不是空的,因为当我在我的视图中执行此操作时:

for host, val1, val2, val3, val4, val5, val6 in combined_data:
        print(host, val1, val2, val3, val4, val5, val6)

I get the output in my console我在控制台中收到 output

10.1.1.1 not found not found not found not found not found not found
10.1.1.2 not found not found not found not found not found not found

Note: 'not found' is the value inside list.注意:“未找到”是列表中的值。 Any insight please?有什么见解吗? thank you谢谢你

The problem was that the zip function returns an iterator, which can only be iterated over once.问题是 zip function 返回一个迭代器,它只能迭代一次。 To fix this, you can convert the zipped object to a list by using the list() function, like so: combined_data = list(zip(hostnames_list, values, values1, values2, values3, values4, values5)).要解决此问题,您可以使用 list() function 将压缩后的 object 转换为列表,如下所示:combined_data = list(zip(hostnames_list, values, values1, values2, values3, values4, values5))。 This way, you can iterate over the combined_data variable multiple times in your template.这样,您可以在模板中多次迭代 combined_data 变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM