如何在Flask和WTForms中设置单选框的默认值

4 投票
2 回答
11256 浏览
提问于 2025-04-18 17:14

我在使用单选框(radio field),我希望默认选中的值显示为 (.) 而不是 ( )。我尝试了一种简单的方法:

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

但是没有成功。它显示的两个选项是:

( ) Choice One
( ) Choice Two

而我希望看到的是:

(.) Choice one
( ) Choice Two

2 个回答

2

如果你和我一样,六年后还在遇到同样的问题,建议你检查一下你的表单类中是否不小心把 coerce=int 设置在了 RadioField 上。这个设置不会报错,但会导致它不接受你在表单类中指定的默认值(比如 default=3),或者用户数据中你指定的默认值。希望这能帮到将来的某个人。

14

对我来说,这个方法很好用:

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() }}

生成的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>

撰写回答