Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django MultiValueField with non-required fields

I'm trying to make a MultiValueField for which the last field is not required.

According to the docs, if I set require_all_fields to False, then I can set some fields to not be required, like this:-

class MyMultiWidget(widgets.MultiWidget):
    def __init__(self, attrs=None):
        _widgets = (
            widgets.TextInput(attrs=attrs),
            widgets.TextInput(attrs=attrs),
            widgets.TextInput(attrs=attrs),
            widgets.TextInput(attrs=attrs),
        )
        super(MyMultiWidget, self).__init__(_widgets, attrs)

    def decompress(self, value):
        return [None, None, None, None]


class MyMultiValueField(forms.MultiValueField):
    widget = MyMultiWidget

    def __init__(self, *args, **kwargs):
        fields = (
            forms.CharField(),
            forms.CharField(),
            forms.CharField(),
            forms.CharField(required=False))
        super(MyMultiValueField, self).__init__(
            require_all_fields=False, fields=fields, *args, **kwargs)

    def compress(self, data_list):
        return data_list

But the HTML that this generates looks like this:-

<input name="field_0" required="" class="textinput textInput form-control" id="id_field_0" autocomplete="off" type="text">
<input name="field_1" required="" class="textinput textInput form-control" id="id_field_1" type="text">
<input name="field_2" required="" class="textinput textInput form-control" id="id_field_2" type="text">
<input name="field_3" required="" class="textinput textInput form-control" id="id_field_3" type="text">

As you can see, all the fields are required. Any idea what I've done wrong here?

like image 613
bodger Avatar asked Oct 29 '25 21:10

bodger


1 Answers

I see this is an old question, but I came across it today and found out the solution is to add required=False to the super call in MyMultiValueField.__init__ so that it becomes:

super(MyMultiValueField, self).__init__(
        required=False, require_all_fields=False, fields=fields, *args, **kwargs)
like image 200
Kukosk Avatar answered Oct 31 '25 12:10

Kukosk



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!