0

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
    }
]

1 Answer 1

0

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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.