Access form field attributes in templated Django

时光毁灭记忆、已成空白 提交于 2019-12-05 05:24:14

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

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

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

{{ form.field_1.field.widget.attrs.maxlength }}

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 }}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!