[英]Using a combination of FieldList and FormField results in exception
I'm using a combination of jinja2 and wtforms for my project, where I'm required to use FormField in a FieldList. 我在我的项目中使用jinja2和wtforms的组合,需要在FieldList中使用FormField。 The following code does not work but throws exception.
以下代码不起作用,但会引发异常。
class FormTranslations(object):
def gettext(self, string):
return gettext(string)
def ngettext(self, singular, plural, n):
return ngettext(singular, plural, n)
class BaseForm(Form):
def __init__(self, request_handler):
super(BaseForm, self).__init__(request_handler.request.POST)
def _get_translations(self):
return FormTranslations()
class SubForm(BaseForm):
name = fields.StringField()
qty = fields.IntegerField()
class MainForm(BaseForm):
value = fields.IntegerField()
items = fields.FieldList(fields.FormField(SubForm), min_entries=2)
#Instantiate and initialize the MainForm:
f = MainForm(self)
Exception:
…
…
…
File "/src/external/wtforms/form.py", line 178, in __call__
return type.__call__(cls, *args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'formdata'
Sometime it is formdata
. 有时是
formdata
。 Some other times, it is obj
or prefix
that seems to be the unexpected
keyword. 在其他时候,它是
obj
或prefix
似乎是unexpected
关键字。
What is wrong with my code? 我的代码有什么问题?
The issue is the constructor for your subform (via BaseForm) accepts different parameters to that of the built-in wtforms "Form" constructor. 问题是您的子窗体的构造函数(通过BaseForm)接受与内置wtforms“窗体”构造函数不同的参数。
The wtforms builtin form init has this signature: def __init__(self, formdata=None, obj=None, prefix='', **kwargs):
wtforms内置表单init具有以下签名:
def __init__(self, formdata=None, obj=None, prefix='', **kwargs):
The FormField object constructs the encapsulated form with the following logic: if isinstance(data, dict): self.form = self.form_class(formdata=formdata, prefix=prefix, **data) else: self.form = self.form_class(formdata=formdata, obj=data, prefix=prefix)
Thus the BaseForm Constructor needs to accept the appropriate parameters to be encapsulated within the FormField object. FormField对象使用以下逻辑构造封装的表单:
if isinstance(data, dict): self.form = self.form_class(formdata=formdata, prefix=prefix, **data) else: self.form = self.form_class(formdata=formdata, obj=data, prefix=prefix)
因此,BaseForm构造方法需要接受适当的参数以封装在FormField对象中。
The solution appears to be either to inherit "Form" in your SubForm, or add the required support to BaseForm. 解决方案似乎是继承您的SubForm中的“ Form”,或向BaseForm添加所需的支持。
I'm currently working through what appears to be the same issue in a webapp2 application and I'm testing having the subform inherit from Form instead of BaseForm with some success. 我目前正在研究webapp2应用程序中似乎存在的相同问题,并且正在测试子窗体继承自Form而不是BaseForm并取得了一些成功。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.