开发者

Accessing initial value of django forms when iterating over the fields

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


how about this?

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


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

{{field.value}}


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

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜