Django form field required conditionally

15,226

Check the Chapter on Cleaning and validating fields that depend on each other in the documentation.

The example given in the documentation can be easily adapted to your scenario:

def clean(self):
    cleaned_data = super(SignupFormExtra, self).clean()
    is_company = cleaned_data.get("is_company")
    nip = cleaned_data.get("NIP")
    if is_company and not nip:
        raise forms.ValidationError("NIP is a required field.")
    return cleaned_data
Share:
15,226

Related videos on Youtube

Efrin
Author by

Efrin

Updated on September 15, 2022

Comments

  • Efrin
    Efrin almost 2 years

    I'd like to have a field which is required conditionally based on setting a boolean value to True or False.

    What should I return to set required =True if is_company is set to True?

    class SignupFormExtra(SignupForm):
        is_company = fields.BooleanField(label=(u"Is company?"), 
                                         required=False)
        NIP = forms.PLNIPField(label=(u'NIP'), required=False)
    
        def clean(self):
            if self.cleaned_data.get('is_company', True):
                return ...?
            else:
                pass
    
  • Seth
    Seth almost 11 years
    The link @arie provided also covers how to associate the error with the field by replacing the raise statement with self._errors["NIP"] = self.error_class(["This is a required field."])
  • Reaz Murshed
    Reaz Murshed almost 4 years
    @Seth thanks for the comment! That was really helpful!