Adding iddentifiable non-field errors

1k Views Asked by At

I am doing some custom validation in the clean method in a ModelForm. I want to add custom non-field error messages, but I need them to be identifiable by some kind of key, so this doesn't work:

self.add_error(None, 'Custom error message 1')
self.add_error(None, 'Custom error message 2')
self.add_error(None, 'Custom error message 3')

I need to be able to tell these apart to render them in an appropriate place in the invalid form template instead of having them all grouped as None non-field errors.

How can I do that?

2

There are 2 best solutions below

0
dirkgroten On BEST ANSWER

Use the ValidationError class, which supports a code parameter in its initialiser. Then instead of getting the strings for the non_field_errors(), fetch the actual data:

self.add_error('__all__', ValidationError("Custom error message", code="type1")
...
for error in self.non_field_errors().data:  # non_field_errors() returns an ErrorList instance
     print(error.code)
0
Nafees Anwar On

I don't think there is a standard way in django for doing that. But you can implement your own little method if you really want that.

class MyForm(forms.Form):
    def add_non_field_error(self, group, error):
        errors = self._errors.setdefault(group, self.error_class(error_class='nonfield'))
        errors.append(error)


f = MyForm(data={})
f.is_valid()  # True
f.add_non_field_error('no_field', 'This is an error.')
f.is_valid()  # False
f.errors  # {'no_field': ['This is an error.']}