Search code examples
djangodjango-forms

How to require only one of two fields at the form level


Users only have to fill out one of two fields.
How would I require this? And where would it be?

I'm trying to put it in the save, but I believe it belongs elsewhere since the validationerror pops up as a Django error screen, and not a field validation error. Here's what I've tried:

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()  

Solution

  • 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()