Django MultiValueField包含非必填字段

问题描述 投票:1回答:1

我正在尝试创建一个不需要最后一个字段的MultiValueField。

根据文档,如果我将require_all_fields设置为False,那么我可以设置一些不需要的字段,如下所示: -

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

但是这个生成的HTML看起来像这样:

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

如您所见,所有字段都是必需的。知道我在这里做错了什么吗?

django django-widget
1个回答
0
投票

我看到这是一个老问题,但我今天遇到它并发现解决方案是将required=False添加到MyMultiValueField.__init__中的超级调用,以便它变为:

super(MyMultiValueField, self).__init__(
        required=False, require_all_fields=False, fields=fields, *args, **kwargs)
© www.soinside.com 2019 - 2024. All rights reserved.