WTForms creating a custom widget

*爱你&永不变心* 提交于 2019-12-01 04:07:11

Answered under Update, but needed this init inside Field derived class.

def __init__(self, label=None, validators=None, text='Save', **kwargs):
    super(InlineButton, self).__init__(label, validators, **kwargs)
    self.text = text

You can take advantage of useful attributes on the field, namely 'description' and 'label' for this instance. This yields a much simpler setup:

from wtforms.widgets.core import HTMLString, html_params, escape

class InlineButtonWidget(object):
    def __call__(self, field, **kwargs):
        kwargs.setdefault('type', 'submit')
        # Allow passing title= or alternately use field.description
        title = kwargs.pop('title', field.description or '')
        params = html_params(title=title, **kwargs)

        html = '<button %s><span>%s</span></button>'
        return HTMLString(html % (params, escape(field.label.text)))

Usage: (wrapped for readability)

class MyForm(Form):
    foo = BooleanField(
        u'Save',
        description='Click here to save',
        widget=InlineButtonWidget()
    )

alternately, to have a field type for it:

class InlineButtonField(BooleanField):
    widget = InlineButtonWidget()

class MyForm(Form):
    foo = InlineButtonField('Save', description='Save Me')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!