2017-04-03 1 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 라이브러리를 좋아해서 내가 어떻게 사용할 수 있는지 궁금해. at (또는 간단히 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> 
관련 문제