Menu Close

How to pass custom form parameters to Formset with Python Django?

To pass custom form parameters to Formset with Python Django, we call formset_factory and functools.partial.

For instance, we write

from functools import partial, wraps
from django.forms.formsets import formset_factory

ServiceFormSet = formset_factory(wraps(ServiceForm)(partial(ServiceForm, affiliate=request.affiliate)), extra=3)

to wrap the ServiceForm with wraps.

And then we call partial with Service and the argument we want to pass into ServiceForm.

And then we call (wraps(ServiceForm with the result returned by partial.

And then we call formset_factory on the result returned by wraps.

Posted in Python, Python Answers