将字段的标签传递给WTForms __init__

时间:2017-01-17 14:32:14

标签: python flask wtforms flask-wtforms

我想将表单字段的标签作为参数传递给表单__init__。现在我收到NameError: name 'self' is not defined错误。

class MyForm(FlaskForm):
    def __init__(self, label_t, **kw):
        super(MyForm, self).__init__(**kw)
        self.label_t = label_t

    name = StringField(self.label_t, validators=[DataRequired()])

f = MyForm("test1", csrf_enabled=False)

我也尝试将name变量放入init函数中, 但我得到AttributeError: 'UnboundField' object has no attribute '__call__'

class MyForm(FlaskForm):
    def __init__(self, label_t, **kw):
        super(MyForm, self).__init__(**kw)
        self.label_t = label_t
        self.name = StringField(self.label_t, validators=[DataRequired()])

如何将字段的标签传递给__init__

1 个答案:

答案 0 :(得分:1)

您无法从类属性访问self,这是NameError的原因。如果您想在__init__上设置字段标签,只需设置实例的label属性:

class MyForm(FlaskForm):

    def __init__(self, label_t, **kw):
        super(MyForm, self).__init__(**kw)
        self.name.label = label_t

    name = StringField(validators=[DataRequired()])