本文介绍了在 FlaskForm (WTForms) 中传递并使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码一目了然 - 我想将一个变量传递给 FlaskForm 子类以供进一步使用.

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)

我得到的是

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?

推荐答案

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

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)

在这里查看我提出的问题:flaskform pass a variable (WTForms)

See the question I asked with my answer here: flaskform pass a variable (WTForms)

这篇关于在 FlaskForm (WTForms) 中传递并使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 22:32