Pass to and use a variable inside a FlaskForm (WTForms)

橙三吉。 提交于 2020-06-28 05:24:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!