Django: For Loop to Iterate Form Fields

不打扰是莪最后的温柔 提交于 2019-12-21 04:09:29

问题


I don't want to use django's built in form generation, seeking to specify each field in my template in order to customize the html output.

How do I iterate over a series of form fields?

If my form looks like this:

class MyForm(forms.Form):
    main_image = forms.ImageField()
    second_image = forms.ImageField()
    third_image = forms.ImageField()
    fourth_image = forms.ImageField()
    ...

Is there way to write a {% for %} loop so that I can iterate through:

{{ form.main_image }}
{{ form.second_image }}
{{ form.third_image }}
{{ form.fourth_image }}

I tried the following which seemed logical, but did not work:

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

回答1:


Well this would clearly not work:

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

but this will:

{% for field in form %}
    {{ field }}
{% endfor %}



回答2:


This one should work :

{% for field in form %}
  {{ field }}
{% endfor %}

Once you loop through field in form , you can't access form.field




回答3:


The best way is to use two loops, one for hidden fields and one for visible fields :

visibles:

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

hiddens:

{% for hidden in form.hidden_fields %}
    {{ hidden }}
{% endfor %}

in this way you will have better control over UI elements.




回答4:


For any frontend developers looking to customize a Django form you can use a package called django-widget-tweaks to render fields individually. Example code below:

{# Your template with the form #}
{% extends "base.html" %}
{% load widget_tweaks %}

<form action="" method="POST">
    {% csrf_token %}

    {% for field in form %}
        <label for="{{ field.id_for_label }}">
          {{ field.label }}{% if field.field.required %}*{% endif %}
        </label>
        {% render_field field %}
    {% endfor %}

    <button type="button">
        Submit Form
    </button>
</form>

Note: You'll want to make this look nicer of course, and you may want to loop through your form errors if there are any.

They have some very useful examples on their PyPi page as well.



来源:https://stackoverflow.com/questions/19123715/django-for-loop-to-iterate-form-fields

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