user8491711
user8491711

Reputation: 91

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

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?

Upvotes: 2

Views: 4201

Answers (2)

SkyTemple
SkyTemple

Reputation: 121

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)

Upvotes: 8

Prashant Singh
Prashant Singh

Reputation: 45

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))

Upvotes: -1

Related Questions