Passing Custom Form parameter to formset

时光总嘲笑我的痴心妄想 提交于 2019-12-04 11:35:33

Digging through django.forms.models you can see that inlineformset_factory needs a form class, not an instance. This is why your last try works and the other fail...passing in an instance won't work.

This should give you what you are looking for:

class MyReadOnlyForm(MyForm):

    def __init__(self, *args, **kwargs):
        super(MyReadOnlyForm,self).__init__(readOnly=True, *args,**kwargs)


Formset = inlineformset_factory(ModelA, ModelB form=MyReadOnlyForm)

If you need both versions

if read_only is True:
    form_class = MyReadOnlyForm
else:
    form_class = MyForm 

Formset = inlineformset_factory(ModelA, ModelB form=form_class)

Thanks. I did find the following in another post and was wondering if one was better than the other.

Formset = inlineformset_factory(ModelA, ModelB form=MyForm)
Formset.form = staticmethod(curry(MyForm, reaOnly=readOnlyvalue))
myFormset = Formset(request.Files, instance=modelAInst)

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