SaeX
SaeX

Reputation: 18711

Checking for widget attribute in Django templates

I'd need to pass some data from my manually generated form to the template, and would need to check the presence of that information there.

I'm generating my form as such (in the __init__ part):

for i in days_in_month:
    self.fields["info_%s" % i] = forms.ChoiceField(label="%s" % i.strftime("%a %d-%m-%Y"), 
    required=False, 
    choices=Information._meta.get_field('info').choices, 
    widget=forms.Select(attrs={'something': 'test'}))

What I would like to do, is to check in the template whether the attribute something is set, and if so, display its value (in the example above: test).

Any idea?

I tried with {{ field.attribute }} as per Access form field attributes in templated Django and the below:

{% for field in form %}
    {{ field.label_tag }} {{ field }}
    {{ field.widget.attrs.something }}
{% endfor %}

... but that doesn't work (invalid).

Ultimately I want to do something similar to:

{% if field.widget.attrs.something %}{{ field.widget.attrs.something }}{% endif %}

Upvotes: 4

Views: 2387

Answers (1)

alexandernst
alexandernst

Reputation: 15089

That would be

{{ field.field.widget.attrs.something }}

Upvotes: 7

Related Questions