如何使用flask和wtforms使radio字段显示默认值

2024-09-21 02:59:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是单选字段,我希望将默认值呈现为(.)而不是()。我尝试了直截了当的方法:

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

它不起作用。它提供两种选择:

( ) Choice One
( ) Choice Two

我想看看这个:

(.) Choice one
( ) Choice Two

Tags: 方法defaultrequiredonechoicesvalidatorstwochoice
1条回答
网友
1楼 · 发布于 2024-09-21 02:59:31

对我来说很好:

示例.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>

相关问题 更多 >

    热门问题