inuasha
inuasha

Reputation: 33

Flask WTF RadioButton show saved value

I am using a RadioField with 3 options for users to select a subscription they would like. The value for the field is then saved to my database for that user. When the user returns to their settings page I would like to show the radio field with the saved value selected. This is my current 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()])

Upvotes: 0

Views: 1142

Answers (1)

MrLeeh
MrLeeh

Reputation: 5589

You have to assign the data of the RadioField to a model. A model can be a database or just a simple dictionary. Here is a simple example for using a dictionary as a model:

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)

Upvotes: 2

Related Questions