giveJob
giveJob

Reputation: 1540

make one field as mandatory in two fields in django forms

I have the form field like this

so

how to make only one field as mandatory either hi or bye. Need at least one field as mandatory and another can optional while submitting the form django

 class MeForm(forms.Form):
        hi = forms.CharField(max_length=100)
        by = forms.CharField(max_length=100)

Upvotes: 4

Views: 1682

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47354

You can override clean method for this:

class MeForm(forms.Form):
    hi = forms.CharField(max_length=100, required=False)
    by = forms.CharField(max_length=100, required=False)

    def clean(self):
        hi = self.cleaned_data.get('hi')
        by = self.cleaned_data.get('by')
        if not hi and not by:
            raise forms.ValidationError('One of fields is required')
        return self.cleaned_data

Upvotes: 4

Related Questions