1
我正在試圖創建一個不需要最後一個字段的MultiValueField。具有非必填字段的Django 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">
正如你所看到的,所有的字段都是必需的。任何想法我在這裏做錯了嗎?