Whenever you use a {{ form.field.errors }} tag in a Django template, the validation message that is displayed is always surrounded with a unordered list tag. This is not ideal for me. Am I able to modify the surrounding validation message html for a form from a reusable package?
1 Answer
From the django docs about looping over a form's fields:
{{ field.errors }}
Outputs a<ul class="errorlist">containing any validation errors corresponding to this field. You can customize the presentation of the errors with a{% for error in field.errors %}loop. In this case, each object in the loop is a simple string containing the error message.
So for example, to wrap each error in <p> tags you would do:
{% for error in field.errors %}
<p>{{ error|escape }}</p>
{% endfor %}
4 Comments
DataGreed
it still outputs as li, rather them just string
Alasdair
@DataGreed not according to the docs I've linked to above: In this case, each object in the loop is a simple string containing the error message.
DataGreed
Actually you have to iterate over form.non_field_errors to get strings
Alasdair
form.non_field_errors are the errors that do not belong to any specific form field. They are different to field.errors, the errors that belong to a particular field.
errorlist, so you can use CSS to style the list as you wish.