0
我想在我的模型clean()方法中更改field的「required」屬性。需要的模型字段
這裏是我的模型:從視圖中添加一個新的參數
class SomeModel(models.Model):
type = models.CharField()
attr1 = models.ForeignKey(Attr1, blank=True, null=True)
attrs2 = models.ForeignKey(Attr2, blank=True, null=True)
現在,我在我的ModelForm __init__
這樣做。 它動態設置所需的字段。
我可以在我的模型中實現相同嗎?我正在使用django-rest-framework API(它使用ModelForm),因此full_clean()
(包括clean_fields()
和clean()
)將會運行。
說我想要attr1/attr2字段,如果類型以字符串開頭。
我知道我可以做這個檢查Model.clean()
,但它會降落到NON_FIELD_ERRORS
然後。
def clean(self):
if self.type.startswith("somestring"):
if self.attr1 is None and self.attr2 is None:
raise ValidationError("attr1 and attr2 are required..")
我寧願看到這些錯誤連接到attR1和attR2位CRC錯誤與簡單的「這是必須填寫」(標準「要求的」 Django的錯誤)。
看吧http://stackoverflow.com/questions/16609703/django-validating-several-fields – stalk