WTForms creating a custom widget

前端 未结 2 1137
情深已故
情深已故 2021-01-12 00:58

The WTForms documentation is woefully inadequate, they don\'t even show you one single example of a custom widget that isn\'t derived from another widget already.

I

2条回答
  •  执念已碎
    2021-01-12 01:45

    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 = ''
            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')
    

提交回复
热议问题