Reputation: 2177
I use to display errors from the forms.py in template using the code below:
{% for key, value in form.errors.items %}
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<strong>Error:</strong> {% if key != '__all__' %}{{ key|title }} {% endif %} - {{ value|striptags }}
</div>
{% endfor %}
But my project is in a different language so I don't want to show the field name but the label name.
I need something like taht
{{ key.label|title }}
{% for key, value in form.errors.items %}
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<strong>Error:</strong> {% if key != '__all__' %}{{ key.label|title }} {% endif %} - {{ value|striptags }}
</div>
{% endfor %}
Forms
class MyForm(forms.ModelForm):
class Meta:
model = MedicalPatient
fields = {'name', ...
}
labels = {'name': '',
...'
}
How to show label names instead of field names?
Upvotes: 1
Views: 285
Reputation: 32244
You can iterate over the form fields and access the label and any errors from the bound field itself
{% for field in form.visible_fields %}
{% for error in field.errors %}
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<strong>Error:</strong>{{ field.label }} - {{ error }}
</div>
{% endfor }
{% endfor %}
This would mean you would have to handle non field errors separately
{% for error in form.non_field_errors %}
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<strong>Error:</strong>{{ error }}
</div>
{% endfor }
I think the assumption is that field errors are usually rendered right next to the field they are for so the form.errors
dict is pretty barebones
Upvotes: 2