模型和管理中的Django字段验证? [英] Django field validation in Model and in Admin?
问题描述
我想为Django模型的特定字段定义自己的验证例程。
我想要在管理表单中显示错误消息,但如果实体由自己的python代码保存,我也希望发生相同的验证。
有没有办法这样做,而不会破坏DRY原则?
I want to define my own validation routine for a particular field of a Django model. I want the error message to be displayed in the admin form but I also want the same validation to take place if the entity is saved by own python code. Is there a way to do this without breaking the DRY principle?
推荐答案
如果要验证一个单独的字段,您可以编写验证器并将其添加到模型中字段。
If you want to validate an individual field, you can write a validator and add it to your model field.
只要模型的 full_clean
方法被调用。当模型表单被验证(包括在Django管理员)中时,它将被运行,但在保存模型实例时不会自动运行 - 您必须手动调用 full_clean
python代码
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()
如果要在保存模型时强制验证器运行,那么你可以覆盖保存方法,并在那里调用 full_clean
。请注意,这将导致验证在使用模型表单和django admin时运行两次。
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.
这篇关于模型和管理中的Django字段验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!