【问题标题】:Flask-WTForms: dynamically create name and id attributesFlask-WTForms:动态创建 name 和 id 属性
【发布时间】:2017-08-28 22:54:57
【问题描述】:

我的表单允许用户为特定数量的篮球队输入特定数量的名称。这些数字会不断更新,所以我需要创建一个动态表单。

假设我有以下 Flask 视图:

@app.route('/dynamic', methods=['GET', 'POST'])
def dynamic():
    teams = ['Warriors', 'Cavs']
    name_count = 2
    return render_template('dynamic.html', teams=teams, name_count=name_count)

以及HTML模板dynamic.html中的如下表格:

<form method='POST' action='/dynamic'>
  {% for team_index in range(teams | count) %}
    {% for name_index in range(name_count) %}
      <input type="text"
             class="form-control"
             id="team{{ team_index }}_name{{ name_index }}"
             name="team{{ team_index }}_name{{ name_index }}">
    {% endfor %}
  {% endfor %}
<form>

产生以下形式:

<form method='POST' action='/dynamic'>
  <input type="text" class="form-control" id="team0_name0" name="team0_name0">
  <input type="text" class="form-control" id="team0_name1" name="team0_name1">
  <input type="text" class="form-control" id="team1_name0" name="team1_name0">
  <input type="text" class="form-control" id="team1_name1" name="team1_name1">
<form>

我喜欢Flask-WTF 库,所以我想知道如何使用它(或简单地使用wtforms)来呈现此表单。我不确定这是否可行,因为 wtforms 需要为每个输入提供硬编码的字段名称。

【问题讨论】:

    标签: python wtforms flask-wtforms


    【解决方案1】:

    想通了。我需要使用 WTForms Fieldlist 和 FormField 附件。

    class PlayerForm(FlaskForm):
        player = Fieldlist(StringField('Player'))
    
    class TeamForm(FlaskForm):
        team = Fieldlist(FormField(PlayerForm))
    
    @app.route('/dynamic', methods=['GET', 'POST'])
    def dynamic():
        teams = ['Warriors', 'Cavs']
        name_count = 2
        # Build dictionary to prepopulate form
        prepop_data = {'team': [{'player': ['' for p in range(name_count)]} for team in teams]}
        # Initialize form
        form = TeamForm(data=prepop_data)
        return render_template('dynamic.html', form=form)
    

    并通过 jinja2 解包(id 和 name 第一个字段的属性 = team-0-player-0):

    <form method="POST" action="/dynamic">
      {{ form.csrf_token }}
      {% for team in form.team %}
        {{ team.csrf_token }}
        {% for player in team.player %}
          {{ render_field(player) }}
        {% endfor %}
      {% endfor %}
    </form>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-22
      • 1970-01-01
      • 2019-07-23
      • 2012-10-12
      • 2020-01-18
      • 1970-01-01
      • 2013-12-24
      • 2018-04-05
      相关资源
      最近更新 更多