In the Django framework, custom model field validation can be implemented in the following ways:
Using the clean()
method : Define a clean()
method in the model to validate the model’s fields. This method is automatically called when invoking the full_clean()
method and is commonly used in form validation.
1 2 3 4 5 6 7 8 from django.core.exceptions import ValidationErrorclass 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 with clean_
followed by the field name.
1 2 3 4 5 6 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 the validators
parameter.
1 2 3 4 5 6 7 8 from django.core.validators import RegexValidatordef 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 the save()
method.
1 2 3 4 5 6 7 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
or post_save
, to perform validation before or after saving the model.
1 2 3 4 5 6 7 from django.db.models.signals import pre_savefrom 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.