Model.clean()
[source]
This method should be used to provide custom model validation, and to modify attributes on your model if desired. For instance, you could use it to automatically provide a value for a field, or to do validation that requires access to more than a single field:
import datetime from django.core.exceptions import ValidationError from django.db import models from django.utils.translation import ugettext_lazy as _ 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(_('Draft entries may not have a publication date.')) # Set the pub_date for published items if it hasn't been set already. if self.status == 'published' and self.pub_date is None: self.pub_date = datetime.date.today()
Note, however, that like Model.full_clean()
, a model’s clean()
method is not invoked when you call your model’s save()
method.
In the above example, the ValidationError
exception raised by Model.clean()
was instantiated with a string, so it will be stored in a special error dictionary key, 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 try: article.full_clean() except ValidationError as e: non_field_errors = e.message_dict[NON_FIELD_ERRORS]
To assign exceptions to a specific field, instantiate the 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.')}) ...
If you detect errors in multiple fields during Model.clean()
, you can also pass a dictionary mapping field names to errors:
raise ValidationError({ 'title': ValidationError(_('Missing title.'), code='required'), 'pub_date': ValidationError(_('Invalid date.'), code='invalid'), })
Finally, full_clean()
will check any unique constraints on your model.
Please login to continue.