Nick Bewley
Nick Bewley

Reputation: 9289

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 %}

Upvotes: 23

Views: 45138

Answers (4)

Kalob Taulien
Kalob Taulien

Reputation: 1893

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.

Upvotes: 4

AmiNadimi
AmiNadimi

Reputation: 5715

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.

Upvotes: 18

user975343
user975343

Reputation:

This one should work :

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

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

Upvotes: 7

mariodev
mariodev

Reputation: 15484

Well this would clearly not work:

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

but this will:

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

Upvotes: 55

Related Questions