Wtforms, add a class to a form dynamically

后端 未结 4 1280
温柔的废话
温柔的废话 2020-12-25 14:01

is there a way i could send a form\'s (css) class from python? For example:

class Company(Form):
    companyName = TextField(\'Company Name\', [validators.Le         


        
4条回答
  •  长发绾君心
    2020-12-25 14:23

    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:

    1. 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:

      {% for field in form %}
      {{field.label}}
      {{field(class_=field.short_name)}}
      {% endfor %}
    2. 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)
      

提交回复
热议问题