summaryrefslogtreecommitdiff
path: root/docs
diff options
context:
space:
mode:
authorAlasdair Nicol <alasdair@thenicols.net>2014-11-18 17:58:43 +0000
committerTim Graham <timograham@gmail.com>2014-11-21 13:01:28 -0500
commit5b26a014a81ba0d404d46e11d2b45c01d92b97e5 (patch)
treeb44176b444a5ce137b8f6a2ba50da0baaac9cdd3 /docs
parenta3aeba0f9535e59133e49374a6485a85f26d756e (diff)
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.
Diffstat (limited to 'docs')
-rw-r--r--docs/ref/models/instances.txt20
1 files changed, 17 insertions, 3 deletions
diff --git a/docs/ref/models/instances.txt b/docs/ref/models/instances.txt
index 21c4c86c13..4e8a1d1ee8 100644
--- a/docs/ref/models/instances.txt
+++ b/docs/ref/models/instances.txt
@@ -200,9 +200,10 @@ access to more than a single field::
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.
-Any :exc:`~django.core.exceptions.ValidationError` exceptions raised by
-``Model.clean()`` will be stored in a special key error dictionary key,
-:data:`~django.core.exceptions.NON_FIELD_ERRORS`, that is used for errors
+In the above example, the :exc:`~django.core.exceptions.ValidationError`
+exception raised by ``Model.clean()`` was instantiated with a string, so it
+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::
from django.core.exceptions import ValidationError, NON_FIELD_ERRORS
@@ -211,6 +212,19 @@ that are tied to the entire model instead of to a specific field::
except ValidationError as e:
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.
.. method:: Model.validate_unique(exclude=None)