Home > Software engineering >  iterating thru fields in html form and passing them to function in python with flask
iterating thru fields in html form and passing them to function in python with flask

Time:04-15

i have following html with n groups of input:

    <form action="{{ url_for('list_names') }}" method="POST">
        <label>Name</label>
        <input name="peson_name" type="text">
        <label>Age</label>
        <input name="person_age" type="number">

        <label>Name</label>
        <input name="peson_name" type="text">
        <label>Age</label>
        <input name="person_age" type="number">
    </form>

i would like to iterate thru every input and pass them to python function using flask and create list of dictionaries

@app.route('/list_names', methods=["GET", "POST"])
def list_names():
    if request.method == 'POST':

and this is where I stuck. the output that i'm looking for is a list of dictionaries that should ideally looks like this:

[
    {
    'name': 'person1',
    'age': 25
    },
    {
    'name': 'person2',
    'age': 30
    }
]

CodePudding user response:

With request.form.getlist(...) all values from input fields with the specified name can be queried. The lists of names and ages obtained in this way can be combined using zip. Thus, pairs are formed from the values that have the same index. Then it is only necessary to form a dictionary from the received tuples.

from flask import (
    Flask,
    render_template,
    request
)

app = Flask(__name__)

@app.route('/list_names', methods=['GET', 'POST'])
def list_names():
    if request.method == 'POST':
        names = request.form.getlist('person_name')
        ages = request.form.getlist('person_age', type=int)
        data = [{ 'name': name, 'age': age } for name,age in zip(names, ages)]
        print(data)
    return render_template('list_names.html')
  • Related