【问题标题】:How can I loop through all the properties of an python object in django templates如何在 django 模板中遍历 python 对象的所有属性
【发布时间】:2018-04-23 18:52:27
【问题描述】:

我有 django 模板,我得到了一些对象。 我想为这个对象的所有属性申请循环。

    {% for point in Object %}
        <h1>{{ Object[point] }}</h1>
    {% endfor %}

【问题讨论】:

标签: python django


【解决方案1】:

您不能在模板中这样做。 一种解决方案是使用object.__dict__ 在视图中的字典中转换您的对象,然后使用以下命令对其进行迭代:

{% for attr, value in object_dict.items %}
    {{ attr }} : {{ value }}
{% endfor %}

正如 py_dude 建议的那样,您可以丢弃以下划线开头的属性以保留您的实际属性。

【讨论】:

    【解决方案2】:
    {% for k, v in Object.__dict__.items() %}
        {% if not k.startswith("_") %}
            <h1>{{ v }}</h1>
        {% endif %}
    {% endfor %}
    

    【讨论】:

    • 这行不通,你不能在模板中使用__dict__
    猜你喜欢
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 2014-02-06
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    • 1970-01-01
    • 2021-10-09
    相关资源
    最近更新 更多