Skip to content

Instantly share code, notes, and snippets.

@titusz
Created November 9, 2016 13:47
Show Gist options
  • Save titusz/1fb67decd3b39ebf0e2402d2703117fa to your computer and use it in GitHub Desktop.
Save titusz/1fb67decd3b39ebf0e2402d2703117fa to your computer and use it in GitHub Desktop.
Extended model validation
class ExtendedValidationModel(models.Model):
"""
Abstract model class that adds conditional field cleaning/validation.
You can create extended field validation with model methods like:
def clean_<fieldname>(self):
# things gone bad
raise ValidationError('whatever')
return self.<fieldname>
To enable extended validation make sure you set
<ModelInstance>.EXTENDED_VALIDATION = True
befor calling <ModelInstance>.full_clean()
"""
class Meta:
abstract = True
EXTENDED_VALIDATION = False
def clean_fields(self, exclude):
if exclude is None:
exclude = []
errors = {}
try:
super(ExtendedValidationModel, self).clean_fields(exclude)
except ValidationError as e:
errors = e.update_error_dict(errors)
if self.EXTENDED_VALIDATION:
for f in self._meta.fields:
if f.name in exclude:
continue
if hasattr(self, "clean_%s" % f.name):
try:
value = getattr(self, "clean_%s" % f.name)()
setattr(self, f.name, value)
except ValidationError as e:
errors = ValidationError({f.name: e.messages})\
.update_error_dict(errors)
if errors:
raise ValidationError(errors)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment