Allow only positive decimal numbers

前端 未结 5 1185
北海茫月
北海茫月 2021-02-01 13:48

Within my Django models I have created a decimal field like this:

price = models.DecimalField(_(u\'Price\'), decimal_places=2, max_digits=12)

O

5条回答
  •  北恋
    北恋 (楼主)
    2021-02-01 14:18

    According to the docs, it seems that there's no way to put something like a database constraint on a field. The best you can do is add model "validators" which will be called if you call model validation or use a ModelForm. The validators are skipped if you simply put values into an object and save().

    So, you can add validation on the forms or you can add validation to the model which also get run on the form level if you use ModelForm.

    From the docs on "How validators are run":

    See the form validation for more information on how validators are run in forms, and Validating objects for how they’re run in models. 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. See the ModelForm documentation for information on how model validation interacts with forms.

提交回复
热议问题