WTForms RadioField default values

房东的猫 提交于 2021-02-18 20:11:43

问题


I'm generating a html form with wtforms like this:

<div class="control-group">
    {% for subfield in form.time_offset %}
    <label class="radio">
        {{ subfield }}
        {{ subfield.label }}
    </label>
    {% endfor %}
</div>

My form class is like this:

class SN4639(Form):
    time_offset = RadioField(u'Label', choices=[
        ('2', u'Check when Daylight saving has begun, UTC+02:00'),
        ('1', u'Check when Daylight saving has stopped, UTC+01:00')],
        default=2, validators=[Required()])

When I now open the edit form, I get via SQL the value 1 or 2 - how can I preset the specifiy radiobutton?


回答1:


default=2 needs to be of type string, not int:

class SN4639(Form):
    time_offset = RadioField(u'Label', choices=[
        ('2', u'Check when Daylight saving has begun, UTC+02:00'),
        ('1', u'Check when Daylight saving has stopped, UTC+01:00')],
        default='2', validators=[Required()])



回答2:


If I understand your question properly, you want to have the form render with a pre-selected choice (rather than returning a default choice if no value is submitted to the form)...

What you can do is construct the form while setting the pre-selected value:

myform = SN4639(time_offset='2')

And then pass myform off to your template to be rendered.




回答3:


Form.__init__ takes a keyword argument obj= which will populate the form from the given object if no formdata or other defaults are provided. Pass the result from the database to that and it should work.



来源:https://stackoverflow.com/questions/16694121/wtforms-radiofield-default-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!