forms.ValidationError() doesn't print any error message to the template

I am following

Suppose that I have the following form:

class SomeForm(forms.Form):
    some_field = forms.CharField()
    def clean(self):
        raise forms.ValidationError("raise an error")

This should print an error message to the template when the form is submitted. But it’s not.

Whereas If I do the following, it works fine:

    def clean(self):
        self.add_error('some_field', "some message")

I am not able to figure out what I am missing, any help would be appreciated. :slight_smile:

This way you’re throwing a non field form validation message. If you want to throw a field specific validation message from a clean method you need to pass a dictionary to `forms.ValidationError’, like this:

def clean(self):
    raise forms.ValidationError({"some_field": "raise an error"})

You’re probably missing {{ form.errors }} in your template.

If you do the equivalent of a non-field error, self.add_error(None, "some message"), that shouldn’t display either until you show the errors in your template.

Yes, thank you @timonweb, @adamchainz, I was missing the declaration of non_field_errors in my template: {{ form.non_field_errors}}.

Should we also add this in the doc I mentioned above?

Yes, non_field_errors, that’s what I meant.

I am not sure it’s worth directly showing the template code - not every project uses’ forms built-in rendering. I guess this sentence could be slightly expanded to mention non_field_errors, and how you should ensure they’re displayed:

In this code, if the validation error is raised, the form will display an error message at the top of the form (normally) describing the problem.

If you open a PR please add a comment with @adamchainz so I see it

Agree, I will send in a pr expanding that sentence to mention about non_field_errors and loop you in.