Django model validator not working on create

后端 未结 4 1751
抹茶落季
抹茶落季 2020-12-30 23:15

I have model with a field validator

from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator

 class MyModel(mode         


        
相关标签:
4条回答
  • 2020-12-30 23:46

    From django documentation:

    Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form.

    https://docs.djangoproject.com/en/3.1/ref/validators/#how-validators-are-run

    0 讨论(0)
  • 2020-12-30 23:54

    The validator only works when you are using models in a ModelForm.

    https://docs.djangoproject.com/en/dev/ref/validators/#how-validators-are-run

    You can perform model validation by overidding clean() and full_clean() methods

    0 讨论(0)
  • 2020-12-30 23:57

    Validators work only with the Forms and model forms. Can't be used with the model definition because it runs at the app side not the DB side.

    0 讨论(0)
  • 2020-12-31 00:09

    Django validation is mostly application level validation and not validation at DB level. Also Model validation is not run automatically on save/create of the model. If you want to validate your values at certain time in your code then you need to do it manually.

    For example:

    from django.core.exceptions import ValidationError
    form app.models import MyModel
    
    instance = MyModel(name="Some Name", size=15)
    try:
        instance.full_clean()
    except ValidationError:
        # Do something when validation is not passing
    else:
        # Validation is ok we will save the instance
        instance.save()
    

    More info you can see at django's documentation https://docs.djangoproject.com/en/1.10/ref/models/instances/#validating-objects

    In administration it works automatically because all model forms (ModelForm) will run model validation process alongside form validation.

    If you need to validate data because it is coming from untrusted source (user input) you need to use ModelForms and save the model only when the form is valid.

    0 讨论(0)
提交回复
热议问题