2

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)?

mzu
  • 759
  • 8
  • 20

1 Answers1

3

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)
mariodev
  • 13,928
  • 3
  • 49
  • 61
  • ... but what if `FieldError: Unknown field(s) ` appear because our Model and MyForm don't know this 'multi_field' - a custom field given in fieldsets of our ModelAdmin and required to be defined in MyForm class. – Sławomir Lenart May 01 '17 at 11:36