Django field validation in Model and in Admin?

自闭症网瘾萝莉.ら 提交于 2019-12-04 03:09:52

If you want to validate an individual field, you can write a validator and add it to your model field.

The validator will be run for the field whenever the model's full_clean method is called. It will be run whenever a model form is validated (including in the Django admin), but it will not automatically run when the model instance is saved - you must call full_clean manually in python code.

m = MyModel(x=20)
m.full_clean() # may raise ValidationError
m.save()

If you wanted to force the validator to run whenever the model is saved, then you could override the save method and call full_clean there. Note that this would cause the validation to run twice when using model forms and the django admin.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!