Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Serhat Teker
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])
Enter fullscreen modeExit fullscreen mode

Withvalidate_positivevalidator 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
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Uomo Universale | Software Engineer | Entrepreneur | builds systems | py:go:js |
  • Location
    127.0.0.1
  • Work
    Software Engineer
  • Joined

More fromSerhat Teker

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp