我正在尝试创建一个不需要最后一个字段的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">
如您所见,所有字段都是必需的。知道我在这里做错了吗?
答案 0 :(得分:0)
我发现这是一个老问题,但我今天遇到了它,并发现解决方案是将required=False
添加到MyMultiValueField.__init__
中的超级调用中,以便它变为:
super(MyMultiValueField, self).__init__(
required=False, require_all_fields=False, fields=fields, *args, **kwargs)