如何访问表单集的成员表单?
我有一个 inline_formset,我正在使用自定义表单。该表单具有我想调用的各种函数。但是,给定表单集的实例,我如何访问该(那些?)表单?
这是一些伪代码:
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))
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))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过
formset.forms
访问表单集的表单。如果 myFormSet.forms[0].foo() 失败,则可能意味着表单集没有任何表单。您还没有告诉我们它以什么方式失败 -
IndexError
?如果您在
inlineformset_factory
中定义formset
,您是否确保它继承自BaseModelFormSet
?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
ininlineformset_factory
, have you made sure it inherits fromBaseModelFormSet
?