WTForms: dynamically create name and id attributes

My form allows the user to enter a specific number of names for a specific number of basketball teams. These numbers are constantly updated so I need to create a dynamic form.

Let's say I have the following Flask view:

@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)

And the following form in the HTML template 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>

Which yields the following 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>

I love the Flask-WTF library so I'm wondering how I can use that (or simply wtforms) to render this form. I'm not sure this is even possible because wtforms requires a hardcoded field name for every input.


Figured this out. I need to use the WTForms Fieldlist and FormField enclosures.

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)

And unpacking via jinja2 ( id and name attributes on first field = 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>
链接地址: http://www.djcxy.com/p/61766.html

上一篇: WTF或WTForms

下一篇: WTForms:动态创建名称和ID属性