0

I'd like to use the following form class in a modelformset. It takes a maps parameter and customizes the form fields accordingly.

class MyModelForm(forms.ModelForm):
    def __init__(self, maps, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        #customize fields here

    class Meta:
        model = MyModel

My question is, how do I use this form in a modelformset? When I pass it using the form parameter like below, I get an exception.

MyFormSet = modelformset_factory(MyModel, form=MyModelForm(maps))

I suspect it wants the form class only, if so how do I pass the maps parameter to the form?

drjeep
  • 1,019
  • 2
  • 9
  • 15
  • Exact duplicate: http://stackoverflow.com/questions/622982/django-passing-custom-form-parameters-to-formset/ – Carl Meyer Jul 27 '09 at 13:12

1 Answers1

2

Keep in mind that Django uses class definition as a sort of DSL to define various things. As such, instantiating at places where it expects the class object will break things.

One approach is to create your own form factory. Something like:

 def mymodelform_factory(maps):
     class MyModelForm(forms.ModelForm):
          def __init__(self, *args, **kwargs):
               super(MyModelForm, self).__init__(*args, **kwargs)
               #use maps to customize form delcaration here
          class Meta:
               model = myModel
     return MyModelForm

Then you can do:

 MyFormSet = modelformset_factory(MyModel, form=mymodelform_factory(maps))
thedz
  • 5,496
  • 3
  • 25
  • 29
  • The downside of defining your class inside a factory function is that you can no longer subclass it. If that bothers you, you can also use this solution: http://stackoverflow.com/questions/622982/django-passing-custom-form-parameters-to-formset/624013#624013 – Carl Meyer Jul 27 '09 at 13:11
  • Ah, good point Carl. I forgot that formset is really only looking for a Callable, and not a Class. – thedz Jul 27 '09 at 16:52