Wtforms,动态添加一个类到窗体 [英] Wtforms, add a class to a form dynamically
问题描述
有没有办法我可以发送表单的(css)类从python?
例如:
is there a way i could send a form's (css) class from python? For example:
class Company(Form):
companyName = TextField('Company Name', [validators.Length(min=3, max = 60)])
,但我想让文本字段拥有 .companyName
的css类,是否可能直接从python?
This renders a simple text field, but i want that text field to have the css class of .companyName
, is that possible directly from python?
我知道我可以直接从python中放入 id =companyName
,而不是类。
I know that i can put a id="companyName"
directly from python, but not class.
帮助。
更新:
我尝试了 class _ =companyName
:
__init__() got an unexpected keyword argument '_class'
推荐答案
WTForms不允许在字段初始化中设置显示选项(如类名)。但是,有几种方法可以解决此问题:
WTForms does not allow you to set display options (such as class name) in the field initialization. However, there are several ways to get around this:
-
如果所有字段都应包含类名称ID,然后只需传入每个字段的
short_name
:
<dl>
{% for field in form %}
<dt>{{field.label}}</dt>
<dd>{{field(class_=field.short_name)}}</dd>
{% endfor %}
</dl>
创建自定义小部件 mixin,它提供类名称:
Create a custom widget mixin that provides the class name:
from wtforms.fields import StringField
from 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,动态添加一个类到窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!