Serhat Teker
Posted on • Originally published attech.serhatteker.com on
Custom Model Field Validator - Django
Django has it's built-invalidators which you can use, however if you want to write your own custom validation:
# models.pyfromdjango.core.exceptionsimportValidationErrorfromdjango.dbimportmodelsfromdjango.utils.translationimportgettext_lazyas_defvalidate_positive(value):ifvalue<0:raiseValidationError(_("%(value)s is not positive."),params={"value":value})classBook(models.Model):author=models.ForeignKey(Author,on_delete=models.CASCADE)title=models.CharField(max_length=120)price=models.DecimalField(validators=[validate_positive])
Withvalidate_positive
validator we ensure thatprice is always positive.
NOTE
validatorsparam always must be alist, even though there isone validator.
By the way you don't need to usegettext_lazy
but it's a good habit fori18n.
All done!
Top comments(0)
Subscribe
For further actions, you may consider blocking this person and/orreporting abuse