2

based upon this answer regarding formset_factory, I tried to do the same thing for modelformset_factory:

from django.utils.functional import curry
from functools wraps

AccountMemberFormSetBase = modelformset_factory(AccountMember,
                                                form=wraps(AccountMemberLimitedModelForm)(curry(AccountMemberLimitedModelForm, affiliate="test")),
                                                extra=2)

This throws the following error:

function() argument 1 must be code, not str
Exception Location: ../django/forms/models.py in modelform_factory, line 528

Any idea whats wrong here?

Community
  • 1
  • 1
Thomas Kremmel
  • 14,575
  • 26
  • 108
  • 177

2 Answers2

1

I found myself in the same situation today.

See my comment in Django Passing Custom Form Parameters to Formset for details and a workaround (I hope a link to StackOverflow itself is acceptable).

Community
  • 1
  • 1
RobM
  • 1,005
  • 11
  • 13
0
class AccountMemberLimitedModelForm(forms.Form):
...     def __init__(self, *args, **kwargs):
...         affiliate = kwargs.pop('affiliate')
...         super(AccountMemberLimitedModelForm, self).__init__(*args, **kwargs)



AccountMemberFormSetBase = formset_factory(AccountMemberLimitedModelForm)
    formset = AccountMemberFormSetBase(form_kwargs={'affiliate': "test"})
  • It would be nice if you posted more than just some code. Perhaps you could explain why that code works? – Mika Sundland Nov 10 '17 at 14:49
  • with kwargs.pop('affiliate') I add external variable to the form. It must be done before calling super(AccountMemberLimitedModelForm, self).__init__(*args, **kwargs) to take effect. And when I pass the variable to form from formset by using form_kwargs dictionary – Rustem Kerimov Nov 10 '17 at 21:45
  • You can get more information from https://docs.djangoproject.com/en/1.11/topics/forms/formsets/#passing-custom-parameters-to-formset-forms – Rustem Kerimov Nov 10 '17 at 21:50