gpt4 book ai didi

python - 使用 Flask wtforms 创建自定义小部件

转载 作者:太空宇宙 更新时间:2023-11-03 14:14:44 26 4
gpt4 key购买 nike

我正在努力寻找解释如何使用 wtforms 创建自定义小部件的资源。我想显示切换按钮列表。到目前为止,我已经能够使用

创建复选框列表
SelectMultipleFields:
class PrecisionForm(FlaskForm):
phone_number = StringField('Phone number', [validators.Length(min=4, max=25)])
contact_emails = SelectMultipleField(
'Contact emails',
[at_least_one],
choices=[],
option_widget=widgets.CheckboxInput(),
widget=widgets.ListWidget(prefix_label=False)
)

但现在我想修改我的 widget.CheckBoxInput()我的自定义小部件如下所示:

<label class='switch'> <input type='checkbox'><span class='slider round'></span></label>

如果有人可以逐步解释如何做到这一点,我将非常感激。

--更新--

我找到了一种方法来实现我想做的事情,但看起来很糟糕:

class ToggleButtonWidget(object):
def __call__(self, field):
html = '<label class="switch"><input type="checkbox" id={} name={} value={}><span class="slider round"></span></label>'.format(field.id, field.name, field.label.__dict__['text'])
return HTMLString(html)

尤其是这部分:field.label.__dict__['text']我用它来设置复选框的值(wtforms 中的字段对象没有属性值)。有更好的办法吗?

最佳答案

输入字段的样式应在前端完成。例如,您将:

class CheckBoxWidget(Form):
box1 = BooleanField()
box2 = BooleanField()
...


widget = FormField(CheckBoxWidget)

然后在你的 html 文件中你会看到类似的内容:

<div>
form.widget.label("checkbox-class")
form.widget("other-checkbox-class")
</div>

包裹在您的表单内。

关于python - 使用 Flask wtforms 创建自定义小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48262191/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com