Wtforms,将类动态添加到表单
有没有办法可以从python发送表单的(css)类?例如:
class Company(Form): companyName = TextField('Company Name', [validators.Length(min=3, max = 60)])
这呈现了一个简单的文本字段,但是我希望该文本字段具有的CSS类.companyName
,是否可以直接从python进行?
我知道我可以id="companyName"
直接从python 放一个,但不能放一个类。
更新:我尝试了class_="companyName"
,但没有成功,我得到了:
__init__() got an unexpected keyword argument '_class'
回答:
WTForms不允许你在字段初始化中设置显示选项(例如类名)。但是,有几种方法可以解决此问题:
如果你所有的字段都应包含一个类名和一个ID,则在short_name呈现它时只需将每个字段的值传递给它即可:
<dl>{% for field in form %}
<dt>{{field.label}}</dt>
<dd>{{field(class_=field.short_name)}}</dd>
{% endfor %}
</dl>
创建一个提供类名称的自定义窗口小部件混合:
from wtforms.fields import StringFieldfrom wtforms.widgets import TextInput
class ClassedWidgetMixin(object):
"""Adds the field's name as a class
when subclassed with any WTForms Field type.
Has not been tested - may not work."""
def __init__(self, *args, **kwargs):
super(ClassedWidgetMixin, self).__init__(*args, **kwargs)
def __call__(self, field, **kwargs):
c = kwargs.pop('class', '') or kwargs.pop('class_', '')
kwargs['class'] = u'%s %s' % (field.short_name, c)
return super(ClassedWidgetMixin, self).__call__(field, **kwargs)
# An example
class ClassedTextInput(ClassedWidgetMixin, TextInput):
pass
class Company(Form):
company_name = StringField('Company Name', widget=ClassedTextInput)
以上是 Wtforms,将类动态添加到表单 的全部内容, 来源链接: utcz.com/qa/413037.html