Access form field attributes in templated Django

django, django-forms, django-templates

Solution

In other cases it can can be useful to set and get field attributes.

Setting in form's init function:

self.fields['some_field'].widget.attrs['readonly'] = True

... and accessing it in a template:

{{ form.some_field.field.widget.attrs.readonly }}

Problem

I've been doing some custom forms with django but I don't get how to access attributes that a specific form field has attached via the forms.py. ``` def putErrorInTitle (cls): init = cls.__init__ def __init__ (self, *args, **kwargs): init(self, *args, **kwargs) if self.errors: for field_error in self.errors: self.fields[field_error].widget.attrs['title'] = self.errors[field_error][0] self.fields[field_error].widget.attrs['class'] = "help_text error_field" cls.__init__ = __init__ return cls ``` That's how I attached the attibutes to the field. ``` <dl class="clearfix two"> <dd> <label for="id_diagnosis">Diagnostico:</label> <select class="{{form.id_diagnosis.class}}" id="id_equipment_activity-{{ forloop.counter0 }}-id_diagnosis" name="equipment_activity-{{ forloop.counter0 }}-id_diagnosis"> {% for x,y in form.fields.id_diagnosis.choices %} <option value="{{ x }}" {% ifequal form.id_diagnosis.data|floatformat x|floatformat %}selected="selected"{% endifequal %}>{{ y }}</option> {% endfor %} <option value="1000" {% ifequal form.id_diagnosis.data|floatformat '1000'|floatformat %}selected="selected"{% endifequal %}>Otro</option> </select> </dd> <dd class="vertical_center" id="optional_diagnosis"><label for="optional_diagnosis">Diagnostico opcional:</label>{{ form.optional_diagnosis }}</dd> </dl> ``` I've been trying to access its attributes: ``` class="{{form.id_diagnosis.class}}", class="{{form.id_diagnosis.widget.class}}" ``` And I don't seem to find clear documentation about what's accessible and what's not. Really I would rather have old fashion documentation than django "friendly" one

Original source