我正在尝试在我的django应用程序中构建自定义多值窗口小部件。
的widget
class DayInputWidget(MultiWidget):
def __init__(self, attrs=None):
widgets = (DayInput(day_name='Mo'), DayInput(day_name='Di'), DayInput(day_name='Mi'), DayInput(day_name='Do'), DayInput(day_name='Fr'))
super(DayInputWidget, self).__init__(widgets, attrs)
def decompress(self, value):
print value
if value:
return value
return None
输入
class DayInput(Input):
input_type = 'text'
def __init__(self,attrs=None,day_name=None):
super(DayInput, self).__init__(attrs)
self.day_name = day_name
def render(self, name, value, attrs=None):
if name is None:
name = 'Bestellmenge_%s' % self.day_name
# create day inputs
return mark_safe(u'<label style="padding-left: 5px">%s</label><input type="text" name="%s" size="5px" value="0"/> ' % (self.day_name,name))
字段
class DayInputField(forms.MultiValueField):
widget = DayInputWidget
def __init__(self, *args, **kwargs):
fields = (forms.CharField(),forms.CharField(),forms.CharField(),forms.CharField(), forms.CharField())
super(DayInputField, self).__init__(fields, *args, **kwargs)
def compress(self, data_list):
print data_list
if data_list:
return u'|'.join(data_list)
return None
表格
class OrderForm(forms.Form):
Produktart = forms.ModelChoiceField(MProductTypes.objects.all())
Kw = forms.CharField(widget=KwSelect(), required=False)
Bestellmengen = fields.DayInputField()
问题:表单仅在绑定到数据时显示。如果我使用空数据初始化表单,则会进行验证并显示。这里有什么问题?
我以这种方式初始化我的表单
form = OrderForm()
根据文件,表格应显示为空。
答案 0 :(得分:0)
尝试以下操作:在widget类中,重写解压缩方法,使其不返回None,但是[]:
class DayInputWidget(MultiWidget):
def __init__(self, attrs=None):
widgets = (DayInput(day_name='Mo'), DayInput(day_name='Di'), DayInput(day_name='Mi'), DayInput(day_name='Do'), DayInput(day_name='Fr'))
super(DayInputWidget, self).__init__(widgets, attrs)
def decompress(self, value):
print value
if value:
return value
return []
这是in this SO answer的建议,它帮助了我一个类似的案例。