(How) can I tell if my form field is hidden in Django template
Asked Answered
C

2

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?)

Conventioneer answered 24/10, 2014 at 16:26 Comment(0)
H
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 %}
Hanse answered 24/10, 2014 at 16:55 Comment(0)
B
1

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 %}
Bosk answered 15/11, 2022 at 6:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.