Validators
Validators
Writing validators
A validator is a callable that takes a value and raises a ValidationError
if it doesn’t meet some criteria. Validators can be useful for re-using validation logic between different types of fields.
For example, here’s a validator that only allows even numbers:
from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ def validate_even(value): if value % 2 != 0: raise ValidationError( _('%(value)s is not an even number'), params={'value': value}, )
You can add this to a model field via the field’s 登录查看完整内容