Inline formset factory - pass request to child form

99封情书 提交于 2019-12-22 17:50:00

问题


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:

  • I tried to use the form= kwarg but I can't pass an instance - just a class. So no way for me to add the request here.
  • I tried to use the formset= kwarg but when I try to pass the request=request as a kwarg of the inlineformset_factory I get an error (Unexpected kwarg)

Any idea what I can do?

Thanks! Ron


回答1:


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)


来源:https://stackoverflow.com/questions/21875555/inline-formset-factory-pass-request-to-child-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!