16👍
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 }}
11👍
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 }}
- Django: Creating a superuser with a custom User model
- How to serialize binary files to use with a celery task
2👍
The above answers are correct, however, I’d like to add a note for those who are accessing form fields in a loop.
If you’re doing this in a loop like this
{% for field in form %}
{{ field.field.widget.attrs.placeholder }} # field.field is the key here
{% endfor %}
- What are some alternative for ModelChoiceField for large number of choices?
- Django ORM, CharField and blank=True
- Django rest framework serializer is valid always false
- Celery does not registering tasks
- Django query filter by number of ManyToMany objects
Source:stackexchange.com