模型和管理员中的Django字段验证?

时间:2022-03-13 08:04:17

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?

我想为Django模型的特定字段定义自己的验证例程。我希望错误消息显示在管理表单中,但如果实体是由自己的python代码保存,我也希望进行相同的验证。有没有办法在不违反DRY原则的情况下做到这一点?

1 个解决方案

#1


9  

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.

只要调用模型的full_clean方法,就会为该字段运行验证器。它将在验证模型表单时运行(包括在Django管理员中),但在保存模型实例时不会自动运行 - 您必须在python代码中手动调用full_clean。

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.

如果您想在保存模型时强制验证器运行,那么您可以覆盖save方法并在那里调用full_clean。请注意,这将导致验证在使用模型表单和django admin时运行两次。

#1


9  

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.

只要调用模型的full_clean方法,就会为该字段运行验证器。它将在验证模型表单时运行(包括在Django管理员中),但在保存模型实例时不会自动运行 - 您必须在python代码中手动调用full_clean。

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.

如果您想在保存模型时强制验证器运行,那么您可以覆盖save方法并在那里调用full_clean。请注意,这将导致验证在使用模型表单和django admin时运行两次。