Django表单:需要两个字段XOR吗?

时间:2013-09-22 15:28:32

标签: django django-forms

我有两个CharFields,我需要制作它,以便用户需要填写其中一个而不是两个(独占或)。是否有捷径可寻?代码:

def __init__(self, *args, **kwargs):
    super(AddMemberByUsernameForm, self).__init__(*args, **kwargs) 
    self.helper = FormHelper()

    self.helper.layout = Layout(
        'username',
        'student_id',
        'title',
        'tags',
        FormActions(
            Submit('save', _('Save changes'))
        )
    )

username = forms.CharField()    #field1
student_id = forms.CharField()  #field2 - these are the two fields
title = forms.CharField()
tags = forms.MultipleChoiceField(
    required=False,
    widget=forms.CheckboxSelectMultiple, 
    choices=[(x.id, x.name) for x in membership_ops.get_all_membership_tags()]
)

1 个答案:

答案 0 :(得分:6)

您应该覆盖表单的clean方法。这是一个例子

def clean(self):
    cleaned_data = super(MyForm, self).clean()

    username = cleaned_data.get("username")
    student_id = cleaned_data.get("student_id")

    if username and student_id: # both were entered
        raise forms.ValidationError("Enter only one of username or student id")
    elif not username and not student_id: # neither were entered
        raise forms.ValidationError("You must enter a username or a student id")

    return cleaned_data