[Django]-Django forms custom validation on two fields one or the other

8👍

✅

You need to handle that in the form’s clean method.
Something like this:

class BatchForm(forms.ModelForm):
    ...
    ...
    def clean(self):
        check = [self.cleaned_data['single'], self.cleaned_data['group']]
        if any(check) and not all(check):
            # possible add some errors
            return self.cleaned_data
        raise ValidationError('Select any one')

3👍

The documentation explains exactly how to validate forms that depend on each other, via the form’s clean() method.

Leave a comment