Search code examples
pythonflaskwtformsflask-wtforms

How to make radio field show default value with flask and wtforms


I am using radio field, and I would like the default value to be rendered as (.) instead of ( ) . I tried straightforward approach:

choice_switcher = RadioField('Choice?', [validators.Required()], choices=[('choice1', 'Choice One'),('choice2', 'Choice Two')], default='choice1')

It didn't work. It renders two choices as:

( ) Choice One
( ) Choice Two

Whereas I'd like to see this:

(.) Choice one
( ) Choice Two

Solution

  • Works alright for me:

    example.py

    from flask import Flask, render_template
    from flask_wtf import Form
    from wtforms import validators, RadioField
    
    app = Flask(__name__)
    
    app.secret_key = 'TEST'
    
    class TestForm(Form):
        choice_switcher = RadioField(
            'Choice?',
            [validators.Required()],
            choices=[('choice1', 'Choice One'), ('choice2', 'Choice Two')], default='choice1'
        )
    
    
    @app.route('/')
    def hello_world():
        testform = TestForm()
        return render_template('test_form.html', form=testform)
    
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    test_form.html

    {{ form.choice_switcher() }}
    

    generated html:

    <ul id="choice_switcher">
        <li><input checked id="choice_switcher-0" name="choice_switcher" type="radio" value="choice1"> <label
                for="choice_switcher-0">Choice One</label></li>
        <li><input id="choice_switcher-1" name="choice_switcher" type="radio" value="choice2"> <label
                for="choice_switcher-1">Choice Two</label></li>
    </ul>