[Django]-Django: Add non_field_error from view?

60đź‘Ť

âś…

You can also use quite elegant add_error() method. Works for Django >= 1.7.

If you set field as None form will treat the error as “non_field” one.
So:

form.add_error(None, "I'm non-field error")

works like a charm.

👤n1_

24đź‘Ť

Adding to Daniel’s answer, the specific syntax is:

form.errors['__all__'] = form.error_class(["error msg"])

Note that you can substitute '__all__' with the constant NON_FIELD_ERRORS for better compatibility (credit grafa).

from django.forms.forms import NON_FIELD_ERRORS
👤mpen

6đź‘Ť

Well, you can insert anything into the form’s errors dictionary, and non-field errors go in errors['__all__'].

But why are you keeping some fields out of the Django form, only to put their errors back in at the end? Why not put all the fields in the form in the first place? If it’s just that you’re using a modelform and you want to add fields to it, you can do this in Django by simply declaring the fields at the form level – then you can define clean methods for them within the form.

class ExtendedModelForm(forms.ModelForm):
    extra_field_1 = forms.CharField()
    extra_field_2 = forms.CharField()

    def clean_extra_field_1(self):
        ...etc...

Leave a comment