Zubair Alam
Zubair Alam

Reputation: 8937

How to get non_field_errors on template when using FormView and ModelForm

I'm using FormView with ModelForm to process a registration form. In case of duplication of email i'm raising ValidationError. But this error message is not available on registration template as non_field_errors.

When i tried to find what is the form.errors in form_invalid method in RegistrationView, its showing the expected the errors, but somehow its not getting passed to template.

Upvotes: 0

Views: 1476

Answers (2)

Sahil kalra
Sahil kalra

Reputation: 9044

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

Upvotes: 1

Jamie Counsell
Jamie Counsell

Reputation: 8123

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 %}

Upvotes: 0

Related Questions