How to conditionally remove form field=required

Viewed 19

It's simple to require a field based on the state of another:

class FooForm(forms.Form)
    foo = forms.BooleanField()
    bar = forms.CharField(required=False)

    def clean(self):
        if self.cleaned_data.get('foo') and not self.cleaned_data.get('bar'):
            raise forms.ValidationError('With foo you must have bar')

How can I do the reverse and remove a field requirement instead (without changing it in the model)?

E.g.

class FooForm(forms.Form)
    foo = forms.BooleanField()
    bar = forms.CharField(required=True)

    def clean(self):
        if not self.cleaned_data.get('foo'):
            # No foo, no bar required
            del bar.required??
1 Answers

Set bar to be not required, and in clean check if foo is False and bar doesn't exist:

class FooForm(forms.Form)
    foo = forms.BooleanField()
    bar = forms.CharField(required=False)

    def clean(self):
        super().clean()
        # No foo and no bar, bad
        if not self.cleaned_data.get('foo') and not self.cleaned_data.get('bar'):
            raise forms.ValidationError("Bar is required without Foo")
Related