Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: For Loop to Iterate Form Fields

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 %}
like image 465
Nick B Avatar asked Oct 01 '13 18:10

Nick B


2 Answers

Well this would clearly not work:

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

but this will:

{% for field in form %}
    {{ field }}
{% endfor %}
like image 117
mariodev Avatar answered Sep 17 '22 19:09

mariodev


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.

like image 28
AmiNadimi Avatar answered Sep 18 '22 19:09

AmiNadimi