在 Materialise 中,您使用属性 name
定义单选按钮的单选组,但 Flask-WTForms 使用属性 name
绑定(bind)输入。
如果我的模板中有以下内容:
{{ form.radio1(type='radio', name='group1') }}
{{ form.radio2(type='radio', name='group1') }}
将会出现错误:
TypeError: html_params() got multiple values for keyword argument 'name'
如果我们不添加名称, radio 将不会像预期那样用作 radio ,而只是作为复选框。
我该如何解决这个问题?
这是我的表单类:
class AbcForm(FlaskForm):
field1 = HiddenField('Field1')
field2 = HiddenField('Field2')
然后在运行时我将动态添加 radio ,这是一个简化:
class F(AbcForm):
pass
setattr(F, radio1, BooleanField('Radio1')
setattr(F, radio2, BooleanField('Radio2')
form = F(field1=x, field2=y)
最佳答案
您无法在字段中设置 name
属性,wtforms 已为您完成此操作。
使用RadioField而不是隐藏字段:
from wtforms import RadioField
from flask_wtf import Form
class YourForm(Form):
radio_group = RadioField('label', choices=[('value','description'),('value_two','some other description')])
(...)
然后,在您的端点中:
@route('/your/route')
def your_endpoint():
your_form = YourForm()
(...)
return render_template('/your/template.html', form=your_form)
最后,在您的模板中:
<form action="#">
{% for subfield in form.radio_group %}
<p>
{{ subfield }}
{{ subfield.label }}
</p>
{% endfor %}
</form>
这会生成以下代码:
<form action="#">
<p>
<input id="radio_group-0" name="radio_group" type="radio" value="value">
<label for="radio_group-0">description</label>
</p>
<p>
<input id="radio_group-1" name="radio_group" type="radio" value="value_two">
<label for="radio_group-1">some other description</label>
</p>
</form>
如果模板中包含了 Materialize,它将正确渲染单选按钮,如 this plunker 所示。 .
关于python - 如何使用 Materialise 和 WTForms 创建单选按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41475015/