[SOLVED] How to conditionally remove form field=required

Issue

This Content is from Stack Overflow. Question asked by alias51

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?

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??



Solution

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


This Question was asked in StackOverflow by alias51 and Answered by pigrammer It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?