我正在创建一个由ChoiceField和CharField组成的MultiValueField。我现在意识到MultiValueFields与.as_hidden模板标签不兼容,所以我查看了django.forms.widgets.SplitDateTimeWidget和django.forms.widgets.SplitHiddenDateTimeWidget实现以获得指导。
class YesNoDateWidget(forms.MultiWidget):
def __init__(self, attrs=None):
_widgets = (
forms.widgets.RadioSelect(attrs=attrs, choices=YESNO_CHOICES),
forms.widgets.TextInput(attrs=attrs),
)
super(YesNoDateWidget, self).__init__(_widgets, attrs)
def decompress(self, value):
print "Decompress: %s" % value
if value:
return [value, value]
return [None, None]
class YesNoDateHiddenWidget(YesNoDateWidget):
def __init__(self, attrs=None):
super(YesNoDateHiddenWidget, self).__init__(attrs)
for widget in self.widgets:
widget.input_type = 'hidden'
class YesNoDateField(forms.fields.MultiValueField):
widget = YesNoDateWidget
hidden_widget = YesNoDateHiddenWidget
def __init__(self, *args, **kwargs):
fields = [
forms.fields.ChoiceField(choices=YESNO_CHOICES),
forms.fields.CharField(),
]
super(YesNoDateField, self).__init__(fields, *args, **kwargs)
这几乎可以工作,在模板中隐藏CharField(使用{%for field in form%} {{field.as_hidden}} {%endfor%}),但仍然会渲染ChoiceField。如果我使用标准ChoiceField(widget = RadioSelect)并使用{{field.as_hidden}},它将呈现为普通字段。
谁能看到我做错了什么?
谢谢, /马丁
答案 0 :(得分:0)
我最终没有继承隐藏字段的YesNoDateWidget类,但基本上是复制它,只是将小部件RadioSelect
和TextInput
切换到HiddenInput
。感觉很多非DRY,但它会使轮子旋转。
class YesNoDateHiddenWidget(forms.MultiWidget):
def __init__(self, attrs=None):
widgets = (
forms.widgets.HiddenInput(attrs=attrs),
forms.widgets.HiddenInput(attrs=attrs),
)
super(YesNoDateHiddenWidget, self).__init__(widgets, attrs)
def decompress(self, value):
print "Decompress: %s" % value
if value:
return [value, value]
return [None, None]