[1.7.x] Fixed #23865 -- documented how to assign errors to a field in Model.clean()

Also added a unit test wit the simpler syntax which we have documented,
where the dictionary values are strings.

Backport of 5b26a014a8 from master
This commit is contained in:
Alasdair Nicol 2014-11-18 17:58:43 +00:00 committed by Tim Graham
parent 910dcd574a
commit f91c6ecc22
3 changed files with 26 additions and 3 deletions

View File

@ -152,9 +152,10 @@ access to more than a single field::
Note, however, that like :meth:`Model.full_clean()`, a model's ``clean()`` Note, however, that like :meth:`Model.full_clean()`, a model's ``clean()``
method is not invoked when you call your model's :meth:`~Model.save()` method. method is not invoked when you call your model's :meth:`~Model.save()` method.
Any :exc:`~django.core.exceptions.ValidationError` exceptions raised by In the above example, the :exc:`~django.core.exceptions.ValidationError`
``Model.clean()`` will be stored in a special key error dictionary key, exception raised by ``Model.clean()`` was instantiated with a string, so it
:data:`~django.core.exceptions.NON_FIELD_ERRORS`, that is used for errors will be stored in a special error dictionary key,
:data:`~django.core.exceptions.NON_FIELD_ERRORS`. This key is used for errors
that are tied to the entire model instead of to a specific field:: that are tied to the entire model instead of to a specific field::
from django.core.exceptions import ValidationError, NON_FIELD_ERRORS from django.core.exceptions import ValidationError, NON_FIELD_ERRORS
@ -163,6 +164,19 @@ that are tied to the entire model instead of to a specific field::
except ValidationError as e: except ValidationError as e:
non_field_errors = e.message_dict[NON_FIELD_ERRORS] non_field_errors = e.message_dict[NON_FIELD_ERRORS]
To assign exceptions to a specific field, instantiate the
:exc:`~django.core.exceptions.ValidationError` with a dictionary, where the
keys are the field names. We could update the previous example to assign the
error to the ``pub_date`` field::
class Article(models.Model):
...
def clean(self):
# Don't allow draft entries to have a pub_date.
if self.status == 'draft' and self.pub_date is not None:
raise ValidationError({'pub_date': 'Draft entries may not have a publication date.'})
...
Finally, ``full_clean()`` will check any unique constraints on your model. Finally, ``full_clean()`` will check any unique constraints on your model.
.. method:: Model.validate_unique(exclude=None) .. method:: Model.validate_unique(exclude=None)

View File

@ -386,6 +386,8 @@ class CustomErrorMessage(models.Model):
def clean(self): def clean(self):
if self.name1 == 'FORBIDDEN_VALUE': if self.name1 == 'FORBIDDEN_VALUE':
raise ValidationError({'name1': [ValidationError('Model.clean() error messages.')]}) raise ValidationError({'name1': [ValidationError('Model.clean() error messages.')]})
elif self.name1 == 'FORBIDDEN_VALUE2':
raise ValidationError({'name1': 'Model.clean() error messages (simpler syntax).'})
elif self.name1 == 'GLOBAL_ERROR': elif self.name1 == 'GLOBAL_ERROR':
raise ValidationError("Global error message.") raise ValidationError("Global error message.")

View File

@ -2207,6 +2207,13 @@ class ModelFormCustomErrorTests(TestCase):
str(form.errors['name1']), str(form.errors['name1']),
'<ul class="errorlist"><li>Model.clean() error messages.</li></ul>' '<ul class="errorlist"><li>Model.clean() error messages.</li></ul>'
) )
data = {'name1': 'FORBIDDEN_VALUE2', 'name2': 'ABC'}
form = CustomErrorMessageForm(data)
self.assertFalse(form.is_valid())
self.assertHTMLEqual(
str(form.errors['name1']),
'<ul class="errorlist"><li>Model.clean() error messages (simpler syntax).</li></ul>'
)
data = {'name1': 'GLOBAL_ERROR', 'name2': 'ABC'} data = {'name1': 'GLOBAL_ERROR', 'name2': 'ABC'}
form = CustomErrorMessageForm(data) form = CustomErrorMessageForm(data)
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())