Custom parameter in Flask-WTFoms field

2019-07-29 00:38发布

问题:

forms.py

my_field = TextField(u"Enter a number", validators=[Required('This Field is Required')])

my_form.html

<table>
  <tr>
    <td colspan="4"> 
      {{form.my_field(placeholder= form.my_field.label.text, class_="form-control")}}
      {% for error in form.my_field.errors %}
          <span>{{error}}</span>
      {% endfor %}
    </td>
  </tr>
</table>

This is a simple code. But I want to follow kind of this to render all the input fields in a loop instead of writing the code for each of them. But each field will have a different colspan value in the corresponding <td>.

How can I add a custom parameter for colspan which I can use in the <td>?

Something like: (just the diff from above code)

forms.py

my_field = TextField(colspan="4")

my_form.html

<td colspan={{form.my_field.colspan}}>

回答1:

You need to create a custom field with an extra colspan attribute.

First define the custom field sub classing TextField:

class MyCustomTextField(TextField):
    def __init__(self, colspan=4, *args, **kwargs):
        super(MyCustomTextField, self).__init__(*args, **kwargs)
        self.colspan = colspan

Now use the custom field in your form:

class MyForm(Form):
    my_field = MyCustomTextField(4, u"Enter a number", validators=[Required('This Field is Required')])

See that first parameter (a 4 in this case) for MyCustomTextField? That's your colspan attribute.

Finally, access the attribute in your template like so:

<td colspan="{{form.my_field.colspan}}">