向inlineformset_factory添加额外的参数 [英] Add extra parameter to inlineformset_factory

查看:48
本文介绍了向inlineformset_factory添加额外的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过几个小时的搜索,我必须承认我被打败了.

After a few hours of searching I must admit that I am defeated.

我已经阅读了Django文档,但确实找不到解决我问题的方法.

I have read the Django docs but I really can't find a solution to my problem.

请考虑以下代码行:

EmploymentFormSet = inlineformset_factory(Profile, Employment, form=EmploymentForm, extra=3)

此代码位于基于类的视图中,该视图继承自 UpdateView ,此外还继承于方法 get_context_data(self,* args,** kwargs):

This code lives in a classbased view which inherits from UpdateView and furthermore in the method get_context_data(self, *args, **kwargs):

这很简单,因为inlineformset_factory创建了EmploymentFormSet.

This is pretty straight forward as the inlineformset_factory creates an EmploymentFormSet.

现在考虑一下

queryset = Employment.objects.filter(profile__pk=self.kwargs['pk']).values()
context['emp_formset'] = EmploymentFormSet(prefix='emp_form', initial=queryset, auto_id=True)

我认为通过提供 initial = queryset (仅适用于未绑定实例IIRC),它会在我的表单集中填充尽可能多的queryset.

I thought by supplying initial=queryset, which only applies to unbound instances IIRC, it would populate my formset with as many as the queryset would contain.

因此,在我的情况下,查询集将返回4个 Employments ,但是当使用 extra 参数时,我正在构造的表单集仅填充了该参数定义的数量,在我的示例中只有3个,因为我仅定义了3个额外功能.增加多余的部分将逐渐填充表格.

So the queryset will in my case return 4 Employments but when using the extra parameter, the formset I'm constructing are only filled with as many as this parameter defines, in my example only 3 since I defined only 3 extras. Incrementing the extra will populate the forms incrementally.

我尝试将 BaseInlineFormSet 子类化,但是我并没有真正突破.

I've tried subclassing the BaseInlineFormSet but I haven't really broken through the wall.

我的问题是我将如何使用查询集所包含的尽可能多的表格填充表单集,我并不是真的想要一个确切的解决方案,而是更多的指向正确方向的指针!:)

My question is how would I go about to populate the formset with as many forms as the queryset contains, I'm not really out for an exact solution but more of a pointer in the right the direction! :)

谢谢!

推荐答案

我通过构造此方法解决了该问题

I solved it by constructing this method

def set_extra_forms(extra_forms, **kwargs):
    EmploymentFormSet = inlineformset_factory(Profile, Employment, form=EmploymentForm, extra=extra_forms)
    return EmploymentFormSet(**kwargs)

现在我确实相信这是要走的路,但是我必须重构代码以使其现在更加动态,因为它仅连接到一个类和一个类,但它就像一种魅力.

Now I do believe this is the way to go but I have to refactor the code in order to make it more dynamic right now its connected to one class and one class only but it works like a charm.

这篇关于向inlineformset_factory添加额外的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆