2016-02-26 64 views
0

我在一个模型中有两个字段,我只想要一个有效的字段在管理员表单中。如果一个字段有效,那么另一个字段不可能插入数据,反之亦然。但是有必要将数据放入两个字段中的一个来保存。Django:两个字段,一个有效

这可能吗?

谢谢!

回答

4

如果您希望验证发生在后端,您将在表格的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

相关问题