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?
Use the
ValidationErrorclass, which supports acodeparameter in its initialiser. Then instead of getting the strings for thenon_field_errors(), fetch the actualdata: