
Custom Validation Methods for Django Model Fields
In the Django framework, custom model field validation can be implemented in the following ways:
-
Using the
clean()
method: Define aclean()
method in the model to validate the model’s fields. This method is automatically called when invoking thefull_clean()
method and is commonly used in form validation.from django.core.exceptions import ValidationError class MyModel(models.Model): my_field = models.CharField(max_length=100) def clean(self): if 'bad_value' in self.my_field: raise ValidationError('my_field cannot contain "bad_value"')
-
Using the
clean_<fieldname>()
method: For validating specific fields, you can define a method prefixed withclean_
followed by the field name.class MyModel(models.Model): my_field = models.CharField(max_length=100) def clean_my_field(self): if 'bad_value' in self.my_field: raise ValidationError('my_field cannot contain "bad_value"')
-
Using the
validators
parameter: When defining a field, you can add custom validators through thevalidators
parameter.from django.core.validators import RegexValidator def my_custom_validator(value): if 'bad_value' in value: raise ValidationError('Value cannot contain "bad_value"') class MyModel(models.Model): my_field = models.CharField(max_length=100, validators=[my_custom_validator])
-
Using the
override
method: If you need to perform validation when saving the model, you can override thesave()
method.class MyModel(models.Model): my_field = models.CharField(max_length=100) def save(self, *args, **kwargs): if 'bad_value' in self.my_field: raise ValidationError('my_field cannot contain "bad_value"') super().save(*args, **kwargs)
-
Using signals: Use Django signals, such as
pre_save
orpost_save
, to perform validation before or after saving the model.from django.db.models.signals import pre_save from django.dispatch import receiver @receiver(pre_save, sender=MyModel) def my_model_pre_save(sender, instance, **kwargs): if 'bad_value' in instance.my_field: raise ValidationError('my_field cannot contain "bad_value"')
These are several common methods for custom field validation in Django models. Choose the appropriate method based on your specific requirements.