Search code examples
djangodjango-formsformsets

Django - Passing Custom Form Parameters to modelfactory


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?


Solution

  • 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})