tags:

views:

104

answers:

1

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?

+2  A: 

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
Thanks, exactly what I was looking for
drjeep
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
Thanks for the link, very informative topic
drjeep
Ah, good point Carl. I forgot that formset is really only looking for a Callable, and not a Class.
thedz