Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize the html output of Django's form validation

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?

like image 566
Mark Stahler Avatar asked Nov 17 '09 00:11

Mark Stahler


People also ask

How do I display validation error in django?

To display the form errors, you use form. is_valid() to make sure that it passes validation. Django says the following for custom validations: Note that any errors raised by your Form.

What is form validation in django?

Django provides built-in methods to validate form data automatically. Django forms submit only if it contains CSRF tokens. It uses uses a clean and easy approach to validate data. The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class.


1 Answers

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 %}
like image 51
Alasdair Avatar answered Nov 07 '22 19:11

Alasdair