wtforms - FieldList 内动态调整的表单

标签 wtforms flask-wtforms

我正在使用 Flask 和 Flask-WTF,我需要创建一个包含多个具有相似结构的 block (子表单)的表单(例如具有一个 SelectField 和一个 TextAreaField 的子表单) )。作为docs suggest ,我可以使用 FormFieldFieldList 来实现这个目标。但是,我需要动态调整我的SelectField(根据数据库中的值在运行时更改其选择)。现在的文档 suggest

Note that the choices keyword is only evaluated once, so if you want to make a dynamic drop-down list, you’ll want to assign the choices list to the field after instantiation.

可以找到这种方法的示例 here 。但是,FormField 接受 form_class,而不是一个实例(至少根据文档),因此这两个方法似乎不能很好地协同工作。

还有其他想法吗?

最佳答案

好吧,比我想象的要容易。您必须创建带有空选项的子表单,创建它们的列表,然后调整列表项内的选项。

class UserForm(wtforms.Form):
# must inherit from wtforms.Form, not flask-WTForms'
# see http://stackoverflow.com/questions/15649027/wtforms-csrf-flask-fieldlist
    first_name = StringField('First Name', [validators.DataRequired()])
    last_name = StringField('Last Name', [validators.DataRequired()])
    accepted_policy = BooleanField('Accept Policy')
    experience = SelectField('Experience', coerce=int)

class UsersForm(Form):
    users = FieldList(FormField(UserForm), min_entries=2)

@app.route('/', methods=['GET', 'POST'])
def hello_world():

    form = UsersForm(users=[{}, {}, {}])
    form.users[0].experience.choices=[(1, 'One'), (2, 'Two')]
    form.users[1].experience.choices = [(1, 'Uno'), (2, 'Du')]
    form.users[2].experience.choices = [(0, 'Zero')]
    return render_template("hello.html", form=form)

这是一个模板:

{% macro render_field(field) %}
  <dt>{{ field.label }}
  <dd>{{ field(**kwargs)|safe }}
  {% if field.errors %}
    <ul class=errors>
    {% for error in field.errors %}
      <li>{{ error }}</li>
    {% endfor %}
    </ul>
  {% endif %}
  </dd>
{% endmacro %}

<form method=post>
  <dl>
      {{ form.hidden_tag()}}
      {%  for user_entry_form in form.users %}
          {{ user_entry_form.name }}
    {{ render_field(user_entry_form.first_name) }}
    {{ render_field(user_entry_form.last_name) }}
    {{ render_field(user_entry_form.experience) }}
      {%  endfor %}
  </dl>
  <p><input type=submit value=Go!>
</form>

关于wtforms - FieldList 内动态调整的表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43159368/

相关文章:

python - 使用 GET 而不是 POST 提交 Wtform

python - 由于缺少 CSRF,表单验证失败

python-3.x - Flask文件下载: filename persists within the session

flask - 如何忽略 Flask-wtf 中的字段验证?

python - Flask-RESTful 与 Flask-WTF 表单集成

python - 为什么我刷新页面WTForms会重新提交?

Python:选择字段 "Not a valid choice"

python - 在 WTForms 中访问 RadioField 的子字段

python - 自定义 Flask-WTF 或 WTForms

python - Flask WTF – 表单总是重定向到 root