首页 > 解决方案 > Django 中的 form.visible_fields 是什么以及如何索引它?

问题描述

有时我需要以特定方式呈现特定的 Django 表单字段。我希望能够访问此字段并且仅访问此字段,以便在我的模板中自定义其呈现。

例如,我知道我可以做这样的事情:

<!--Access the form field at index 2-->
{% for field in form.visible_fields %}
    {% if forloop.counter == 2 %}
        <!--Render my form field the way that I want to-->
    {% endif %}
{% endfor %}

直觉上,我希望能够做类似{{ form.visible_fields[2] }}或可能的事情{{ form.visible_fields['field_name'] }}

不幸的是,我在上面的各种尝试都失败了,所以我想知道这是否可能。有什么建议吗?

标签: djangodjango-formsdjango-templates

解决方案


根据 Django文档,您应该能够执行以下操作:

{# Include the hidden fields #}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{# Include the visible fields #}
{% for field in form.visible_fields %}
    <div class="fieldWrapper">
        {{ field.errors }}
        {{ field.label_tag }} {{ field }}
    </div>
{% endfor %}

推荐阅读