Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 749
giveJob Avatar asked Oct 27 '25 07:10

giveJob


1 Answers

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
like image 58
neverwalkaloner Avatar answered Oct 30 '25 07:10

neverwalkaloner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!