Django:两个字段,一个有效

时间:2016-02-26 14:56:28

标签: django django-models

我在一个模型中有两个字段,我只想在管理表单中有一个有效字段。如果一个字段有效,则另一个字段无法插入数据,反之亦然。但是有必要将数据放在两个字段之一中进行保存。

那可能吗?

谢谢!

1 个答案:

答案 0 :(得分:5)

如果您希望在后端进行此验证,则应在表单的clean方法中进行验证。像这样的东西:

class MyAdminForm(forms.ModelForm):
    def clean(self):
        cd = self.cleaned_data
        fields = [cd['field1'], cd['field2']]
        if all(fields):
            raise ValidationError('Please enter one or the other, not both')
        if not any(fields): #Means both are left empty
            raise ValidationError('Please enter either field1 or field2, but not both')

    return cd

Here is the documentation on using forms with django admin

如果您希望验证在前端发生,而不是在表单提交上,您可能需要考虑使用javascript解决方案。 以下是javascript solution

的答案
相关问题