2
votes

I'm trying to do something pretty simple; I'd like to apply a "hidden" style to a form field inside a django template when I've passed in some initial value like this:

form = form_class(initial={'field':data})

Normally, it would be like this:

<li class="{{form.somefield.name}} {% if form.somefield.initial %} hidden{% endif %}>
    ...
</li>

But I'm iterating over the forms, so what I want do do is something that looks like this:

{% for field in form %}
    <li class="{{field.name}} {% if field.initial %} hidden{% endif %}">
    ...
    </li>
{% endfor %}

but this doesn't work, because field.initial only has the value defined as initial to the field in the form, not the data that's passed in at the form's creation. Is there a good solution for this besides just breaking out the iterating into individual forms?

Some (bad) solutions I've thought of:

  • overriding init to stuff values form self.initial into self.fields;
  • writing a template tags called {% hideifhasinitial %}
  • adding a method to the form that uses zip on self and self.initial (doesn't work, since self.initial only had one element and self had 4, it only iterated over 1 element, and the keys (field names) didn't match up).
4

4 Answers

4
votes

how about this?

{% for field in form %}
    {% if field.name in field.form.initial.keys %}
        ...
    {% endif %}
{% endfor %}
2
votes

Initial data can be accessed on the value attribute, initial data represents the value of the field:

{{field.value}}

0
votes

Turns out there's a way easier way to do this.

{% if field.name in form.initial.keys %}
0
votes

The solution with the initial keys has not worked for me, because the field contains as a value an empty string. I had to write my own custom tag:

from django import template
register = template.Library()

@register.simple_tag
def field_empty(field):
    if not field.form.initial.get(field.name):
        return ' hidden'

    return ''

In your example, I would use the tag this way:

<li class="{{ field.name }} {% field_empty field %}">