9

I have a Django model formset, and some fields have hidden inputs.

I am trying to generate the headings from the first item in the formset with formset.visible_fields. This works.

<table>
<tr>
    {% for myfield in formset.0.visible_fields  %} 
         <th> {{ myfield.name }}</th>
    {% endfor %}
</tr>

{%for form in formset %}
    <tr>
    {% for field in form %}
        <td>{{ field }}</td>
    {% endfor %}
    </tr>
{% endfor%}
</table>

The problem is that the hidden fields don't get a heading. But when I am iterating through my form fields, the hidden field is still getting wrapped with a tag. So I get a column for every field, but a heading for only the visible fields.

Is there a way to check in advance if my field is hidden? (Or is there a better way to hide the headings / fields?)

wobbily_col
  • 11,390
  • 12
  • 62
  • 86

2 Answers2

31

Hidden fields do have a property. Here's the docs about them.

Code from the docs:

{# Include the hidden fields #}
{% for hidden in form.hidden_fields %}
    {{ hidden }}
{% endfor %}

{# Include the visible fields #}
{% for field in form.visible_fields %}
    <div class="fieldWrapper">
        {{ field.errors }}
        {{ field.label_tag }} {{ field }}
    </div>
{% endfor %}
schillingt
  • 13,493
  • 2
  • 32
  • 34
0

If you have to work only with a field, for example, a field named foo, you can easily check if is visible in the template.

{% if form.foo.is_hidden %}
   {# render the field here #}
{% else %}
   {# do something here you need if the field is visible #}
   {# render the field here #}
{% endif %}
Karim N Gorjux
  • 2,880
  • 22
  • 29