问题
The code is pretty self-explanatory - I want to pass a variable to a FlaskForm
subclass for further use.
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)
What I get instead is
line 22, in FooForm
bar_field = StringField("Label's last word is 'bar': {0}".format(self.bar))
NameError: name 'self' is not defined
How do I achieve the desired?
回答1:
I had a very similar problem to this and it took me a while to figure it out. What you want to do can be accomplished like so:
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)
See the question I asked with my answer here: flaskform pass a variable (WTForms)
回答2:
put your bar_field = StringField("Label's last word is 'bar': {0}".format(self.bar))
inside init() method.
use this:
class FooForm(FlaskForm):
def __init__(self, bar):
super(FooForm, self).__init__()
self.bar = bar
self.bar_field = StringField("Label's last word is 'bar': {0}".format(self.bar))
来源:https://stackoverflow.com/questions/47621904/pass-to-and-use-a-variable-inside-a-flaskform-wtforms