Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
636 views
in Technique[技术] by (71.8m points)

django: form.fields not iterating through instance fields

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...