Wtforms, Add A Class To A Form Dynamically
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)]) T
Solution 1:
Alternatively you can add the class in your template like this for jinja2:
{{ form.name(size=20, class_='input-small') }}
Solution 2:
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:
If all of your fields should include a class name as well as an ID then just pass in each field's
short_name
to it when you render it:<dl> {% for field in form %} <dt>{{field.label}}</dt><dd>{{field(class_=field.short_name)}}</dd> {% endfor %} </dl>
Create a custom widget mixin that provides the class name:
from wtforms.fields import StringField from wtforms.widgets import TextInput classClassedWidgetMixin(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) returnsuper(ClassedWidgetMixin, self).__call__(field, **kwargs) # An exampleclassClassedTextInput(ClassedWidgetMixin, TextInput): passclassCompany(Form): company_name = StringField('Company Name', widget=ClassedTextInput)
Solution 3:
Use render_kw
if using WTForms >= 2.1 :
submit = SubmitField(u'Block Submit Buttom', render_kw={"class": "btn btn-primary btn-block"})
Solution 4:
In your template, try it
{{ form.companyName( **{'class': 'companyName'} ) }}
Post a Comment for "Wtforms, Add A Class To A Form Dynamically"