我正在尝试基于动态创建其字段的MultiValueField创建自定义窗口小部件。有点像:
class MyField(MultiValueField):
def __init__(self, my_param, *args, **kwargs):
fields = []
for field in my_param.all():
fields.append(forms.ChoiceField(
widget=forms.Select(attrs={'class':'some_class'})))
super(MyField, self).__init__(
self, fields=tuple(fields), *args, **kwargs)
使用如下字段的表单:
class MyForm(forms.Form):
multi_field = MyField()
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['multi_field'].my_param = self.initial['car_types'].another
此刻我不知所措。当只能从MyForm的构造函数中知道param时,如何将参数(例如my_param)传递给MyField的 init ()方法(例如self.initial ['car_types']。另一个)?
答案 0 :(得分:3)
您需要在__init__
:
class MyForm(forms.Form):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['multi_field'] = MyField(self.initial['car_types'].another)