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