答案 0 :(得分:0)
我所做的是:
from wtforms import SelectField, SelectMultipleField
def _add_chosen_class(kwargs):
'''
Add the class 'chosen-select' to the HTML elements, keeping any
other specified render parameters or other classes.
'''
if 'render_kw' in kwargs:
if 'class' in kwargs['render_kw']:
kwargs['render_kw']['class'] += ' chosen-select'
else:
kwargs['render_kw']['class'] = 'chosen-select'
else:
kwargs['render_kw'] = {'class': 'chosen-select'}
class ChosenSelectField(SelectField):
'''A select field rendered with chosen'''
def __init__(self, *args, **kwargs):
_add_chosen_class(kwargs)
super(ChosenSelectField, self).__init__(*args, **kwargs)
class ChosenSelectMultipleField(SelectMultipleField):
'''A multiple-select field rendered with chosen'''
def __init__(self, *args, **kwargs):
_add_chosen_class(kwargs)
super(ChosenSelectMultipleField, self).__init__(*args, **kwargs)
然后,您可以在表单中声明ChosenSelect[Multiple]Field
。
在Javascript方面,您必须执行常规选择的spiel,包括chosen.min.js
并运行(假设使用jQuery)
$('.chosen-select').chosen({/* chosen-config here */})
注意:
如果需要您的字段,此方法将不会在提交时显示任何错误弹出窗口,因为选择的内容会隐藏原始的<select>
。您将不得不采用其他方式(也许是CSS)。