我正在使用带有3个选项的RadioField,供用户选择他们想要的订阅。然后,该字段的值将保存到该用户的数据库中。当用户返回其设置页面时,我想显示已选择保存值的无线电字段。 这是我目前的RadioFIeld。
subscription_tier = RadioField('Plan', choices=[(tier_one_amount, tier_one_string),
(tier_two_amount, tier_two_string), (tier_three_amount, tier_three_string)],
validators=[validators.Required()])
答案 0 :(得分:2)
您必须将RadioField的数据分配给模型。模型可以是数据库,也可以只是简单的字典。以下是使用字典作为模型的简单示例:
from flask import Flask, render_template
from wtforms import RadioField
from flask_wtf import Form
SECRET_KEY = 'development'
app = Flask(__name__)
app.config.from_object(__name__)
my_model = {}
class SimpleForm(Form):
example = RadioField(
'Label', choices=[('value', 'description'),
('value_two', 'whatever')]
)
@app.route('/', methods=['post','get'])
def hello_world():
global my_model
form = SimpleForm()
if form.validate_on_submit():
my_model['example'] = form.example.data
print(form.example.data)
else:
print(form.errors)
# load value from model
example_value = my_model.get('example')
if example_value is not None:
form.example.data = example_value
return render_template('example.html',form=form)
if __name__ == '__main__':
app.run(debug=True)