@@ -200,9 +200,10 @@ access to more than a single field::
200
200
Note, however, that like :meth:`Model.full_clean()`, a model's ``clean()``
201
201
method is not invoked when you call your model's :meth:`~Model.save()` method.
202
202
203
- Any :exc:`~django.core.exceptions.ValidationError` exceptions raised by
204
- ``Model.clean()`` will be stored in a special key error dictionary key,
205
- :data:`~django.core.exceptions.NON_FIELD_ERRORS`, that is used for errors
203
+ In the above example, the :exc:`~django.core.exceptions.ValidationError`
204
+ exception raised by ``Model.clean()`` was instantiated with a string, so it
205
+ will be stored in a special error dictionary key,
206
+ :data:`~django.core.exceptions.NON_FIELD_ERRORS`. This key is used for errors
206
207
that are tied to the entire model instead of to a specific field::
207
208
208
209
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::
211
212
except ValidationError as e:
212
213
non_field_errors = e.message_dict[NON_FIELD_ERRORS]
213
214
215
+ To assign exceptions to a specific field, instantiate the
216
+ :exc:`~django.core.exceptions.ValidationError` with a dictionary, where the
217
+ keys are the field names. We could update the previous example to assign the
218
+ error to the ``pub_date`` field::
219
+
220
+ class Article(models.Model):
221
+ ...
222
+ def clean(self):
223
+ # Don't allow draft entries to have a pub_date.
224
+ if self.status == 'draft' and self.pub_date is not None:
225
+ raise ValidationError({'pub_date': 'Draft entries may not have a publication date.'})
226
+ ...
227
+
214
228
Finally, ``full_clean()`` will check any unique constraints on your model.
215
229
216
230
.. method:: Model.validate_unique(exclude=None)
0 commit comments