【问题标题】:How to make radio field show default value with flask and wtforms如何使用烧瓶和 wtforms 使无线电字段显示默认值
【发布时间】:2014-08-13 23:15:21
【问题描述】:

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

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

没有用。它呈现两种选择:

( ) Choice One
( ) Choice Two

而我想看到这个:

(.) Choice one
( ) Choice Two

【问题讨论】:

    标签: python flask wtforms flask-wtforms


    【解决方案1】:

    对我来说没问题:

    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>
    

    【讨论】:

    • 谢谢!原来我使用的是一些奇怪的宏而不是 wtforms
    【解决方案2】:

    如果您在六年后遇到同样的问题,就像我一样,您可能会检查您是否不小心在表单类的 RadioField 上设置了coerce=int。除了拒绝遵守表单类中指定的默认值(例如default=3)或您在用户数据的路由中指定的默认值外,这会静默失败。希望有一天这对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 2013-07-11
      • 2021-10-23
      • 2016-01-23
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 2019-07-16
      • 2020-01-22
      • 2016-02-06
      相关资源
      最近更新 更多