gpt4 book ai didi

python - 传递并使用 FlaskForm (WTForms) 内的变量

转载 作者:行者123 更新时间:2023-12-01 02:23:56 24 4
gpt4 key购买 nike

代码非常不言自明 - 我想将变量传递给 FlaskForm 子类以供进一步使用。

from flask import Flask, render_template_string
from flask_wtf import FlaskForm
from wtforms import StringField
from flask_wtf.csrf import CSRFProtect


app = Flask(__name__)
spam = 'bar'
app.secret_key = 'secret'
csrf = CSRFProtect(app)

@app.route('/')
def index():
eggs = spam
form = FooForm(eggs)
return render_template_string(
'''
{{ form.bar_field.label }} {{ form.bar_field }}
''',form = form)

class FooForm(FlaskForm):
def __init__(self, bar):
super(FooForm, self).__init__()
self.bar = bar
bar_field = StringField("Label's last word is 'bar': {0}".format(self.bar))

if __name__ == '__main__':
app.run(debug=True)

我得到的是

line 22, in FooForm
bar_field = StringField("Label's last word is 'bar': {0}".format(self.bar))
NameError: name 'self' is not defined

如何达到预期目标?

最佳答案

我遇到了与此非常相似的问题,我花了一段时间才弄清楚。你想做的事情可以像这样完成:

from wtforms.fields.core import Label

class FooForm(FlaskForm):
bar_field = StringField("Label does not matter")


@app.route('/')
def index():
eggs = 'bar'
form = FooForm()
form.bar_field.label = Label("bar_field", "Label's last word is 'bar': {0}".format(eggs))

return render_template_string(
'''
{{ form.bar_field.label }} {{ form.bar_field }}
''',form = form)

请参阅我提出的问题及其答案:flaskform pass a variable (WTForms)

关于python - 传递并使用 FlaskForm (WTForms) 内的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47621904/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com