Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 216
Alexander Putilin Avatar asked Dec 07 '22 00:12

Alexander Putilin


2 Answers

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>
like image 112
Doobeh Avatar answered Dec 10 '22 12:12

Doobeh


If you're coming to this question with the same problem six years later, like I did, you might check whether you have accidentally set coerce=int on the RadioField in your form's class. This fails silently except for refusing to honour the default specified either in the form class (e.g. default=3), or the default you specify in the route from the user's data. Hope this helps someone some day.

like image 34
George Avatar answered Dec 10 '22 10:12

George