django 如何在表单级别只要求两个字段中的一个

aoyhnmkz  于 2023-04-22  发布在  Go
关注(0)|答案(2)|浏览(112)

用户只需填写两个字段中的一个。
我怎么会需要这个?它会在哪里?
我试着把它放到保存中,但我相信它属于其他地方,因为validationerror弹出的是Django错误屏幕,而不是字段验证错误。

class SignupForm(forms.Form):
    learn1 = forms.CharField(max_length=50, label='Learn', required=False)
    teach1 = forms.CharField(max_length=50, label='Teach', required=False)

    class Meta:
        model = Profile

    def save(self, user):
        if not self.cleaned_data['learn1'] or self.cleaned_data['teach1']:
            raise forms.ValidationError("Specify at least one")
        user.is_profile_to.learn1 = self.cleaned_data['learn1']
        user.is_profile_to.teach1 = self.cleaned_data['teach1']
        user.save()
        user.is_profile_to.save()
inb24sb2

inb24sb21#

def clean(self):
        cleaned_data = super().clean()
        if not self.cleaned_data['learn1'] and not self.cleaned_data['teach1']:
            raise forms.ValidationError("Specify at least one")
        else:
            return cleaned_data

def save(self, user):
        user.is_profile_to.learn1 = self.cleaned_data['learn1']
        user.is_profile_to.teach1 = self.cleaned_data['teach1']
        user.save()
        user.is_profile_to.save()
kq0g1dla

kq0g1dla2#

为了完整起见,您也可以在视图级别(特别是基于类的)处理这个问题。您可以使用form.add_error()并返回form_invalid()

class MyView( FormView): # or UpdateView, etc.

    # usual definitions

    def form_valid( self, form):
        if not form.cleaned_data['learn1'] and not form.cleaned_data['teach1']:
            form.add_error('', 'You must specify either "Learn" or "Teach"')
            return self.form_invalid( form)

        super().form_valid( form)  # if you want the standard stuff, or

        # process the form
        # return a response

form.add_error的第一个参数是要附加错误的表单字段的名称。''指定非表单错误。您可能希望将同一个错误附加到两个字段,在这种情况下只需附加两个错误

form.add_error('learn1', 'You must specify either "Learn" or "Teach"')
        form.add_error('teach1', 'You must specify either "Learn" or "Teach"')
        return self.form_invalid( form)

这样做可以让你访问视图上下文来决定是否有错误。你可以咨询url args或kwargs,或者考虑谁是用户。

相关问题