summaryrefslogtreecommitdiff
path: root/docs/ref
diff options
context:
space:
mode:
authorMatthias Kestenholz <mk@feinheit.ch>2017-04-23 12:55:07 +0200
committerTim Graham <timograham@gmail.com>2017-06-13 20:47:58 -0400
commita1c6c220e2ac86a74869d0017cd658115cc4ad7b (patch)
tree473eeee5279ed8b97a998d086c10551e2fb02eb1 /docs/ref
parent31d7fc85410c81932a42c4d5bb84759fd9f4a295 (diff)
[1.11.x] Fixed #27434 -- Doc'd how to raise a model validation error for a field not in a model form.
Backport of e8c056c31a5b353e7b50a405c00db12c28f4a756 from master
Diffstat (limited to 'docs/ref')
-rw-r--r--docs/ref/models/instances.txt29
1 files changed, 29 insertions, 0 deletions
diff --git a/docs/ref/models/instances.txt b/docs/ref/models/instances.txt
index 2ec7a9bd06..696e09ba57 100644
--- a/docs/ref/models/instances.txt
+++ b/docs/ref/models/instances.txt
@@ -322,6 +322,35 @@ pass a dictionary mapping field names to errors::
Finally, ``full_clean()`` will check any unique constraints on your model.
+.. admonition:: How to raise field-specific validation errors if those fields don't appear in a ``ModelForm``
+
+ You can't raise validation errors in ``Model.clean()`` for fields that
+ don't appear in a model form (a form may limit its fields using
+ ``Meta.fields`` or ``Meta.exclude``). Doing so will raise a ``ValueError``
+ because the validation error won't be able to be associated with the
+ excluded field.
+
+ To work around this dilemma, instead override :meth:`Model.clean_fields()
+ <django.db.models.Model.clean_fields>` as it receives the list of fields
+ that are excluded from validation. For example::
+
+ class Article(models.Model):
+ ...
+ def clean_fields(self, exclude=None):
+ super(Article, self).clean_fields(exclude=exclude)
+ if self.status == 'draft' and self.pub_date is not None:
+ if exclude and 'status' in exclude:
+ raise ValidationError(
+ _('Draft entries may not have a publication date.')
+ )
+ else:
+ raise ValidationError({
+ 'status': _(
+ 'Set status to draft if there is not a '
+ 'publication date.'
+ ),
+ })
+
.. method:: Model.validate_unique(exclude=None)
This method is similar to :meth:`~Model.clean_fields`, but validates all