views:

48

answers:

2

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).
A: 

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

{% if field.name in form.initial.keys %}
Chad
+2  A: 

how about this?

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