我面临着一项相当具有挑战性的任务:
我需要一个 inlineformset_factory
将我的 ParentEntity
连接到我的外键绑定(bind) ChildEntities
。
我的 ChildEntity
包含我需要针对每个登录用户进行过滤的外键关系 - 因此我需要 ChildForm
中的请求。
到目前为止我已经尝试过:
- 我尝试使用
form=
kwarg,但无法传递实例 - 只是一个类。所以我无法在这里添加请求。 - 我尝试使用
formset=
kwarg,但是当我尝试将request=request
作为inlineformset_factory
的 kwarg 传递时,我得到了错误(意外的 kwarg)
知道我能做什么吗?
最佳答案
有时询问同事甚至比 StackOverflow
还要快:)
这是我的解决方案:
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)
关于django - 内联表单集工厂 - 将请求传递给子表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21875555/