trubliphone
trubliphone

Reputation: 4504

how to access the member forms of a formset?

I have an inline_formset for which I am using a custom form. That form has various functions that I would like to call. But, given an instance of the formset, how can I access that (those?) form(s)?

Here is some pseudo-code:

    class MyModel(models.Model):
        myField = models.ForeignKey(MyOtherModel)

    class MyOtherModel(models.Model):
        myField = models.CharField()

    class MyModelForm(forms.ModelForm):
        class Meta:
            model = MyModel

    class MyOtherModelForm(forms.ModelForm):
        class Meta:
            model = MyOtherModel
        def foo(self):
          print "foo"

    MyFormSet = inlineformset_factory(MyModel,MyOtherModel,formset=MyOtherForm)

    def MyView(request):
        myModel = MyModel()
        myForm = MyModelForm(instance=myModel)
        myFormSet = MyFormSet(intance=myModel)

        # THIS FAILS...
        myFormSet.foo()
        # SO DOES THIS...
        myFormSet.forms[0].foo()
        # SO DOES THIS...
        myFormSet.form.foo()
        # ANY IDEAS?

        return render_to_response('my_view.html', {"form" : myForm, "formset" : myFormSet },context_instance=RequestContext(request))    

Upvotes: 0

Views: 200

Answers (1)

Alasdair
Alasdair

Reputation: 309019

You can access a formset's forms through formset.forms.

If myFormSet.forms[0].foo() fails then that probably means the formset does not have any forms. You haven't told us in what way it fails - IndexError?

If you are defining the formset in inlineformset_factory, have you made sure it inherits from BaseModelFormSet?

Upvotes: 1

Related Questions