将字段标签传递给 WTForms __init__

Pass label for field to WTForms __init__

我想将表单字段的标签作为参数传递给表单的 __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__

您无法从 class 属性访问 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()])