Access Form Field Attributes in a Django Template

I make some custom forms with django, but I don't understand how to access attributes that are attached by a specific form field through form.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 

The way I attached 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 am trying to access its attributes:

 class="{{form.id_diagnosis.class}}", class="{{form.id_diagnosis.widget.class}}" 

And I, it seems, did not find clear documentation about what is available and what is not. In fact, I'd rather have the old fashion documentation than the “friendly” django.

+6
source share
2 answers

It looks like you just want to display form errors for each field. After the form is cleared or validated in the view, the fields should contain error messages. So that you can display them in the template as follows:

 <form action='.' method='post'> ... <div class='a-field'> {{ form.field_1.errors|join:", " }} {{ form.field_1.label_tag }} {{ form.field_1 }} </div> ... </form> 

If you really want to display the attributes of a form field, then you can try something like:

 {{ form.field_1.field.widget.attrs.maxlength }} 
+9
source

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

Setting in the init function:

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

... and access to it in the template:

 {{ form.some_field.field.widget.attrs.readonly }} 
+6
source

Source: https://habr.com/ru/post/917122/


All Articles