django - 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'] }}
。
不幸的是,我在上面的各种尝试都失败了,所以我想知道这是否可能。有什么建议吗?
解决方案
根据 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 %}
推荐阅读
- rust - 为什么在 Rust 元组模式匹配中需要显式借用?
- ios - 如何让 UITests-Runner 能够访问隐私敏感数据
- java - itext - setSimpleColumn 无法理解 llx、lly、urx、ury
- javascript - 如何在 JavaScript 中准备嵌套的键值对列表
- c++ - C++ std::getline() 没有设置 EOF 标志
- python-2.7 - Tk 类没有属性“框架”
- c++ - 参考类构造函数定义私有函数
- sql - 如何引用 UNION 的列
- java - 当我尝试连接到 mysql 数据库时,主机名显示不同?
- scala - 无形:类类型参数上的镜头编译错误