0

I have a Django ModelForm like this:

class ContactPhoneForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ContactPhoneForm, self).__init__(*args, **kwargs)
    #....

...and a view where I try to get a respective formset:

ContactPhoneFormSet = modelformset_factory(ContactPhone,
                                           ContactPhoneForm, 
                                           extra=1, 
                                           can_delete = True)

Now, I want an additional parameter to be passed to the __init__method of the form:

 class ContactPhoneForm(forms.ModelForm):
        def __init__(self, contact_id, *args, **kwargs):    
            self.contact_id = contact_id
            super(ContactPhoneForm, self).__init__(*args, **kwargs)
        #....

I tried to the rewrite my view according to this post:

ContactPhoneFormSet = modelformset_factory(ContactPhone,
                                           wraps(ContactPhoneForm)(partial(ContactPhoneForm, contact_id=contact_id)), 
                                           extra=1, 
                                           can_delete = True)

but I end up with TypeError: the first argument must be callable error. Any help on this?

Edgar Navasardyan
  • 4,261
  • 8
  • 58
  • 121

1 Answers1

1

Django 1.9 added a form_kwargs arguement so you should be able to do:

ContactPhoneFormSet = modelformset_factory(
    ContactPhone, ContactPhoneForm, extra=1, can_delete=True)
formset = ContactPhoneFormSet(form_kwargs={'contact_id': contact_id})
laidibug
  • 1,179
  • 8
  • 5
  • Wow :) Thank you. Maybe you should post your answer here as well (https://stackoverflow.com/questions/622982/django-passing-custom-form-parameters-to-formset). And just for the future - can you think of the place you came to know this info ? – Edgar Navasardyan Jul 06 '17 at 08:42