将自定义表单参数传递给表单集 [英] Passing Custom Form parameter to formset

查看:90
本文介绍了将自定义表单参数传递给表单集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了以下表单

class MyForm(ModelForm):  
    def __init__(self, readOnly=False, *args, **kwargs):  
      super(MyForm,self).__init__(*args,**kwrds)  
      if readOnly:  
        Do stuff to make the inputs readonly

当我在视图中将其实例化为窗体时,MyForm完美运行

form = MyForm(readOnly = True,instance = ModelA)

MyForm works perfectly when I instantiate it in the view as a form
form = MyForm(readOnly=True, instance=ModelA)

但是当我尝试在inlineformset_factory中使用它时

Formset = inlineformset_factory(ModelA,ModelB form = MyForm(readOnly = True))

我收到错误消息 NoneType对象不可调用。

but when I try to use it in the inlineformset_factory
Formset = inlineformset_factory(ModelA, ModelB form=MyForm(readOnly=True))
I get the error "NoneType object is not callable."

我认为这是因为表单是在没有模型实例的情况下初始化的

,因为MyForm是在内联中初始化的

I think this is because the form is being initialised without a model instance
because MyForm is being initialised within the inline

我知道问题是我在内联调用中使用MyForm的方式

,因为如果执行以下任一操作,我会得到相同的错误

I know the problem is the way I am using the MyForm in the inline call
because I get the same error if I do either of the following

Formset = inlineformset_factory(ModelA,ModelB form = MyForm(readOnly = True))

Formset = inlineformset_factory(ModelA,ModelB form = MyForm())

但是如果我这样做,它会起作用

Formset = inlineformset_factory(ModelA,ModelB form = MyForm)

but it works if I do
Formset = inlineformset_factory(ModelA, ModelB form=MyForm)

很显然,readOnly参数默认为False,而我的输入是没有改变。
有人知道我可以使用inlineformset_factory将readOnly参数传递给MyForm还是我可以实现我想要的东西?

obviously the readOnly param defaults to False and my inputs are not changed. Does anyone know how I can pass the readOnly param to MyForm using the inlineformset_factory or how else I can achieve what I want?

感谢
Andrew

Thanks Andrew

推荐答案

浏览 django.forms.models ,您会看到 inlineformset_factory 需要表单 class ,而不是实例。这就是为什么上一次尝试有效而其他失败...在实例中传递失败的原因。

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)

这篇关于将自定义表单参数传递给表单集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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