Passing a Custom Form parameter to a form set

I have the following form defined

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 works fine when I create it as a form
form = MyForm(readOnly=True, instance=ModelA)

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

I think this is because the form is initialized without an instance of the model
because myform is initialized inside the inline

I know the problem is how I use MyForm in an inline call
because I get the same error if I do one of the following

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

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

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

Thanks Andrew

+4
source share
2 answers

Digging through django.forms.models , you can see that inlineformset_factory needs a form class, not an instance. This is why your last attempt works, and the other fails ... instance transfer will not 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) 
+4
source

Thanks. I found the following in another post and wondered if it 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)

+1
source

All Articles