[Answered ]-Django: Transferring/Accessing forms full error message

1đź‘Ť

âś…

It would be better to add errors to the actual form. Forms have an _errors dict attached to them that contain all the errors generated by the form. “Non-field errors” (errors that don’t directly relate to a particular field or that relate to multiple fields) go in form._errors['__all__']. All field-specific errors go into the key of the field’s name. So, errors for a foo field would go in form._errors['foo'].

Now, the list of errors for each item in the _errors dict is actually an ErrorList type, not a standard list. So, to add errors to the form you do:

from django.forms.util import ErrorList

form._errors.setdefault('foo', ErrorList()).append('Some error here')

Or, to add the error to non-field errors:

form._errors.setdefault('__all__', ErrorList()).append('Some error here')

Then, when your form renders, the errors will all fall naturally where they should, just like any normal validation error.

👤Chris Pratt

1đź‘Ť

The array probably looks like error[i].field[i].error, so you’re just calling the fieldname and not the error message. Call e.error in your Template() function.

👤Stieffers

Leave a comment