WTForms creating a custom widget

前端 未结 2 1136
情深已故
情深已故 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 = '<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')
    
    0 讨论(0)
  • 2021-01-12 01:49

    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
    
    0 讨论(0)
提交回复
热议问题