djangodjango-formsinline-formset

Inline formset factory - pass request to child form


I'm facing a quite challenging taks:

I need an inlineformset_factory connecting my ParentEntity to my foreign key-bound ChildEntities.

My ChildEntity contains a foreign key relation I need to filter per logged-in user - so I need the request in the ChildForm.

What I've tried so far:

Any idea what I can do?


Solution

  • Sometimes asking a colleague is even faster than StackOverflow :)

    Here's my solution:

    forms.py

    class BaseFormSet(BaseInlineFormSet):
    
    def __init__(self, *args, **kwargs):
    
        self.request = kwargs.pop("request", None)
    
        super(BaseFormSet, self).__init__(*args, **kwargs)
    

    views.py

    MyFormSet = inlineformset_factory(ParentEntity, ChildEntity, formset=BaseFormSet, form=ChildForm, extra=2, max_num=max_num, can_delete=False)
    ...
    formset = MyFormSet(request.POST, instance=obj, request=request)