wobbily_col
wobbily_col

Reputation: 11941

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

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

Upvotes: 9

Views: 8104

Answers (2)

Karim N Gorjux
Karim N Gorjux

Reputation: 3033

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

Upvotes: 1

schillingt
schillingt

Reputation: 13731

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

Upvotes: 31

Related Questions