我如何创建WTForms字段子类?

时间:2012-09-18 15:05:49

标签: python inheritance wtforms

我正在尝试从wtforms的默认字段类创建子类。

class MyForm(Form):
    fieldName = MyField('field name')

并从另一个文件导入MyField

class MyField(TextField):
    def __init__(self):
        super(MyField, self).__init__(**kwargs)

但是当我在这里创建一个MyForm时出现了一些错误:

In [5]: f = MyForm()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
path/<ipython-input-5-decc3699f7c4> in <module>()
----> 1 f = RegistrationForm()

path/wtforms/form.pyc in __call__(cls, *args, **kwargs)
    176             fields.sort(key=lambda x: (x[1].creation_counter, x[0]))
    177             cls._unbound_fields = fields
--> 178         return type.__call__(cls, *args, **kwargs)
    179 
    180     def __setattr__(cls, name, value):

path/wtforms/form.pyc in __init__(self, formdata, obj, prefix, **kwargs)
    222             of a matching keyword argument to the field, if one exists.
    223         """
--> 224         super(Form, self).__init__(self._unbound_fields, prefix=prefix)
    225 
    226         for name, field in iteritems(self._fields):

pathwtforms/form.pyc in __init__(self, fields, prefix)
     37 
     38         for name, unbound_field in fields:
---> 39             field = unbound_field.bind(form=self, name=name, prefix=prefix, translations=translations)
     40             self._fields[name] = field
     41 

path/wtforms/fields/core.pyc in bind(self, form, name, prefix, translations, **kwargs)
    299 
    300     def bind(self, form, name, prefix='', translations=None, **kwargs):
--> 301         return self.field_class(_form=form, _prefix=prefix, _name=name, _translations=translations, *self.args, **dict(self.kwargs, **kwargs))
    302 
    303     def __repr__(self):

TypeError: __init__() got an unexpected keyword argument '_form'

我认为_form字段没有正确实例化。 任何想法如何做到这一点? 谢谢

1 个答案:

答案 0 :(得分:1)

您的MyField.__init__方法缺少必需的关键字args。试试这个:

class MyField(TextField):
    def __init__(self, **kwargs):  # You were missing the **kwargs
        super(MyField, self).__init__(**kwargs)

函数调用中的***运算符(?)执行以下操作:

  • 如果在函数签名中使用,则指定所有剩余的位置(*)或关键字(**)参数应分别放在tuple / dict中)并且数据应绑定到* / **
  • 之后的名称
  • 如果在调用函数中使用,则指定tuplelist(针对*)或dict(针对{{1}应该解压缩并作为参数/关键字参数列表传递给函数。