Home > Enterprise >  Django form optional field still required error
Django form optional field still required error

Time:05-05

I have in my model the following fields:

field1 = models.CharField(max_length=63, null=True, blank=True)
field2 = models.CharField(max_length=255, null=True, blank=True)

and in my form, which extends ModelForm, I haved added:

    field1 = forms.CharField(required=False)
    field2 = forms.CharField(required=False)

    class Meta:
        model = TestForm
        fields = [
            'another_field', 'field1', 'field2'
        ]

But if I don't fill field1 and field2, I get the following error:

TestForm with errors: <ul ><li>__all__<ul ><li>You must specify either a field1 or a field2</li></ul></li></ul>

AFAIK I woudn't even need to set required=False since the model has already set null and blank as true, so what am I missing? Thanks in advance.

CodePudding user response:

I was so worried about the form class, but it turns out someone on the project had already overridden the clean method on the model itself:

def clean(self) -> None:
        if not (self.field1 or self.field2):
            raise ValidationError("You must specify either a field1 or a field2")
        return super().clean()

By removing the lines above, the code now works!

CodePudding user response:

Try edit your form like this:

class My_Form(forms.ModelForm):
class Meta:
    model = TestForm
    fields = ('another_field', 'field1' , 'field2')

def __init__(self, *args, **kwargs):
    super(My_Form, self).__init__(*args, **kwargs)
    self.fields['field1'].required = False
    self.fields['field2'].required = False
  • Related