本文介绍了内联格式工厂 - 将请求传递给子表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正面临一个非常具有挑战性的挑战:我需要一个 inlineformset_factory
连接我的 ParentEntity
到我的外键绑定 ChildEntities
。
我的 ChildEntity
包含一个外键关系,我需要过滤每个登录用户 - 所以我需要在 ChildForm
中的请求。 p>
目前为止我已经尝试过:
- 我试图使用
form =
kwarg,但我不能传递一个实例 - 只是一个类。所以我没有办法在这里添加请求。 - 我试图使用
formset =
kwarg,但是当我尝试传递request = request
作为inlineformset_factory
的kwarg我收到错误(意外的kwarg)
任何想法我可以做什么?
谢谢!
Ron
解决方案
有时要求同事比 StackOverflow
:)
这是我的解决方案:
forms.py p>
class BaseFormSet(BaseInlineFormSet):
def __init __(self,* args,** kwargs):
self.request = kwargs.pop(request)
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 .POST,instance = obj,request = request)
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 therequest=request
as a kwarg of theinlineformset_factory
I get an error (Unexpected kwarg)
Any idea what I can do?
Thanks!Ron
解决方案
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")
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)
这篇关于内联格式工厂 - 将请求传递给子表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!