[Django]-Django: For Loop to Iterate Form Fields

51👍

Well this would clearly not work:

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

but this will:

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

17👍

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.

7👍

This one should work :

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

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

3👍

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.

Leave a comment