【问题标题】:How can I iterate multiple key from a dictionary in Django template如何从 Django 模板中的字典中迭代多个键
【发布时间】:2014-04-27 18:08:30
【问题描述】:

我已经在 django 中将视图中的数据提供给模板。我想迭代这多个键来构建一个 html 表。

views.py

data={'pacientes':p,'inicios':i,'finales':f,'enfermedad':enf} # p, i and f are lists
return render(request,'verEnf.html',data)

我想做类似的事情

index.html

 <table>
     {% for p, i, f in pacientes, inicios, finales %} # I know that this code is not work
        <tr>
            <td>{{ p.nombre }}</td>
            <td>{{ i }}</td>
            <td>{{ f }}</td>
        <tr>
     {% endfor %}
 </table>

p 是 Pacientes 的一个对象

class Usuario(models.Model):
    dni=models.CharField(max_length=9,primary_key=True)
    clave=models.CharField(max_length=16)
    nombre=models.CharField(max_length=30)
    ...

而 i 是一个字符串的列表

('20-2-2014', '12-2-2014', ..., '11-5-2014')

【问题讨论】:

  • 在尝试将其转换为 Django 模板之前,请考虑用 Python 将其写出来。
  • 所以去做吧!真正的问题是什么?

标签: python django templates loops


【解决方案1】:

我想paciente、inicio和finales的每一个索引都是相互关联的。

正如 Ignacio 所说,您可以在视图中编写一些代码,然后将其传递给模板以解决您的问题。 一种可能的解决方案是将值打包在一个元组列表中,如下所示:

[
  (pacientes[0], inicios[0], finales[0]),
  (pacientes[1], inicios[1], finales[1]),
  ...
]

您可以通过在视图中使用zip 函数轻松实现此目的:

pacientes_data = zip(p, i, f)
data={'pacientes_data':pacientes_data,'enfermedad':enf} # p, i and f are lists
return render(request,'verEnf.html',data)

在你的模板中:

<table>
     {% for p,i,f in pacientes_data %}
        <tr>
            <td>{{ p.nombre }}</td>
            <td>{{ i }}</td>
            <td>{{ f }}</td>
        </tr>
     {% endfor %}
</table>

【讨论】:

    猜你喜欢
    • 2015-09-28
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 2012-07-27
    • 2019-02-05
    • 2013-04-30
    • 2018-07-31
    • 1970-01-01
    相关资源
    最近更新 更多