Custom parameter in Flask-WTFoms field

浪尽此生 提交于 2020-01-05 05:27:10

问题


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}}">


来源:https://stackoverflow.com/questions/39544715/custom-parameter-in-flask-wtfoms-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!