Sunday, August 13, 2017
Turning Django Form error into plain text in Templates
Turning Django Form error into plain text in Templates
Django would add an Asterisk before an error message if you do something like this:
{% for fields in form %}
{{ fields.label_tag }}
{{ fields }}
{{ fields.errors }}
{% endfor %}
Which is quite annoying if you are used to working with plain HTML document (AKA the front end guy) like me, we are used to dealing with plain text, not formatted text.
Whereas Django templates render the error messages as unordered lists for us automatically, here is how we may get the plain text version of the error message passed into the template by Python exceptions
{% for fields in form %}
{{ fields.label_tag }}
{{ fields }}
{% for error in fields.errors %}
{{ error }}
{% endfor %}
{% endfor %}
Then you will have the plain text version of error in your template, you make wrap the {{ error }} tag with a p or h1 element if you feels like it, then add custom CSS class to the wrapper element.
To render all errors of a form, use
{{ form.errors }}
To render the field name and error message manually in {{ form.errors}}
{% for field, error in form.errors %}
{{ field }}
{{ error }}
{% endfor %}
Omit the {{ field }} in the above snippet to render only the message
To render only the error message in {{ form.errors }} and as PLAIN TEXT,
{% for field, errors in form.errors %}
{% for error in errors %}
{{ error }}
{% endfor %}
{% endfor %}
Similarly, when an error message is rendered as plain text, you may wrap it with HTML tags to customize them with standard HTML+CSS codes
Enjoy
download file now