2017-04-03 62 views
0

我的表單允許用戶爲特定數量的籃球隊輸入特定數量的名稱。這些數字不斷更新,所以我需要創建一個動態表單。Flask-WTForms:動態創建名稱和ID屬性

比方說,我有以下瓶觀點:

@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圖書館,所以我想知道如何使用th在(或簡單地wtforms)呈現此表單。我不確定這是甚至可能的,因爲wtforms需要每個輸入的硬編碼字段名稱。

回答

0

想通了。我需要使用WTForms FieldlistFormField機箱。

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>