django: form.fields not iterating through instance fields

倾然丶 夕夏残阳落幕 提交于 2019-12-17 19:29:02

问题


I am trying to iterate through form.fields in a template and for:

{% for field in form.fields %}
   {{ field }}, 
{% endfor %}

I am getting a list of the field names ("name, description...") instead of the html code that is rendered when using the following:

{{ form.name }}, {{ form.description }}

(the output in this case is:

<input id="id_name" type="text" name="name" maxlength="200" /><input id="id_description"....

Any hints? Thanks!


回答1:


You want to iterate over "form," not "form.fields". The latter returns Field instances, the former returns BoundField instances (even in the case of an unbound form), which render their widget HTML.

form.visible_fields and form.hidden_fields are utility methods to only get the visible/hidden fields of the form, but they also return BoundField instances. They are not in any way parallel to form.fields (I agree that this isn't the clearest possible API).




回答2:


Iterating "form" instead over "form.fields" solved the problem. Not sure why as the documentation also provides examples such as:

{% for field in form.visible_fields %}
...

which also results in empty sets. Has to do with the fact that my form is not bound? not sure...




回答3:


The field you get are of django.forms.Field instances. To get the html view from it, you can use the widget function. {{ field.widget }}



来源:https://stackoverflow.com/questions/670711/django-form-fields-not-iterating-through-instance-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!