python - Render form errors with the label rather than field name -


i list form errors using {{ form.errors }} in template. produces list of form fields , nested lists of errors each field. however, literal name of field used. generated html error in particular field might this.

<ul class="errorlist">     <li>         target_date_mdcy         <ul class="errorlist">             <li>this field required.</li>         </ul>     </li> </ul> 

i use errorlist feature, it's nice , easy. however, want use label ("target date", say) rather field name. actually, can't think of case in want field name displaying user of webpage. there way use rendered error list field label?

i don't see simple way this.

the errors attribute of form returns errordict, class defined in django.forms.utils - it's subclass of dict knows produce ul rendering of unicode representation. keys field names, , that's important maintain other behavior. provides no easy access field labels.

you define custom template tag accepts form produce rendering prefer, since in python code it's easy field label given form , field name. or construct error list label in view, add context, , use instead.

edit alternately again, can iterate on fields , check individual errors, remembering display non_field_errors well. like:

<ul class="errorlist">   {% if form.non_field_errors %}     <li>{{ form.non_field_errors }}</li>   {% endif %}   {% field in form %}     {% if field.errors %}       <li>         {{ field.label }}         <ul class="errorlist">           {% error in field.errors %}             <li>{{ error }}</li>           {% endfor %}         </ul>       </li>     {% endif %}   {% endfor %} </ul> 

you might want wrap non_field_errors in list well, depending.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -