Provide API method for appending errors
|Reported by:||Owned by:||nobody|
|Cc:||bronger@…||Triage Stage:||Design decision needed|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
On occasion form errors only come to light after a form has been validated. There should be an method to add errors to a form after validation is complete.
A common scenario is for unique database fields. If you test whether the value is unique when cleaning, you introduce a race condition, because the value won't be saved until later. The safe method is this:
if form.is_valid(): try: form.save() except IntegrityError: form._errors['my_unique_field'] = form.error_class([u"This value already exists. Please choose again"]) else: ...
This works well, but this is an implementation-specific, undocumented method. I'd propose something like
form['my_unique_field'].add_error(u"This value must be unique")
for field-specific errors and
form.add_error(u"This combination of foo and bar already exists")
for non-field errors. These would either raise an error if validation had not yet occurred, or attempt validation before appending the error.