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

4 Answers 4

5

how about this?

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

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

{{field.value}}

0

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

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.