我正在尝试基于动态创建其字段的 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 的构造函数(例如 self.initial['car_types'].another)中知道参数时,如何将参数(例如 my_param)传递给 MyField 的init () 方法?