【问题标题】:Using a combination of FieldList and FormField results in exception使用 FieldList 和 FormField 的组合会导致异常
【发布时间】:2015-11-20 00:10:45
【问题描述】:

我在我的项目中使用了 jinja2 和 wtforms 的组合,我需要在 FieldList 中使用 FormField。以下代码不起作用但抛出异常。

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'

有时是formdata。在其他时候,objprefix 似乎是 unexpected 关键字。

我的代码有什么问题?

【问题讨论】:

    标签: wtforms formfield fieldlist


    【解决方案1】:

    问题是子表单的构造函数(通过 BaseForm)接受与内置 wtforms“表单”构造函数不同的参数。

    wtforms 内置表单 init 具有以下签名: def __init__(self, formdata=None, obj=None, prefix='', **kwargs):

    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 对象中。

    解决方案似乎是在您的 SubForm 中继承“Form”,或者向 BaseForm 添加所需的支持。

    我目前正在解决 webapp2 应用程序中似乎相同的问题,并且我正在测试让子表单继承自 Form 而不是 BaseForm 并取得了一些成功。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-13
      • 2018-11-26
      相关资源
      最近更新 更多