I am trying to create a custom widget based on a MultiValueField that dynamically creates its fields. Something along the lines of:
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)
And a form using the field like this:
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
I am somehow stuck at the moment. How can I pass a parameter (e.g. my_param) to MyField's init() method when the param is only know from within MyForm's constructor (e.g. self.initial['car_types'].another)?
You need to instantiate your field inside __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)