[Answer]-How to get non_field_errors on template when using FormView and ModelForm

1👍

First of all, We will have to make sure if its a non_field_error or a field error.

Where have you raise ValidationError in the ModelForm you have defined ?

  1. If its raised in def clean() of the Form, then it would be present in non_field_errors and can be accessed via form.non_field_errors in template

  2. If it is raised in def clean_<field_name>() then, it would be a field error and can be accessed via form.errors or form.<field_name>.error in template

Please decide for yourself where do you want to raise it.

Note: ModelForm can work with with FormView. But Ideally, there are CreateView and UpdateView for that

0👍

Something like this?

{% if my_form.non_field_errors %}
    <div class="alert alert-error">
    <ul>
        {% for error in my_form.non_field_errors %}
            <li>{{ error }}</li>
        {% endfor %}
    </ul>
    </div>
{% endif %}

Leave a comment