2

我有两个 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()]
)
4

1 回答 1

7

您应该覆盖表单的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
于 2013-09-22T15:39:42.177 回答