Django formset factory with arguments

February 2nd, 2009 | by dan |

So a form in your formset needs some arguments, like the current user, in order to build a ChoiceField or whatever. Sounds pretty common but I couldn’t find a built in way to do this. So I created my own formset_factory:

from django.forms.formsets import BaseFormSet
def my_formset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
can_delete=False, max_num=0, request=None):
"""Return a FormSet for the given form class."""
setattr(form, 'request', request)
attrs = {'form': form, 'extra': extra,
'can_order': can_order, 'can_delete': can_delete,
'max_num': max_num, 'request':request}
return type(form.__name__ + 'FormSet', (formset,), attrs)</span>

<span style="text-decoration: line-through;">

I’ve just used setattr() to add the request each form in the formset. The forms can access it as self.request.


Post a Comment