Home > other >  Using <input> inside for loop in jinja flask
Using <input> inside for loop in jinja flask

Time:12-02

I am struggling to figure out how to access individual <input> elements, that have been created through a for loop. For example:

<form id="score" method="POST" action="/div">
    <div class="formInput">
        {% for i in range(2) %}
            <input type="text" class="sFixed" id="scoreFixed">
        {% endfor %}
    </div>
</form>

As you can see, I'm creating two input element's in my form. However, if I try to retrieve the data that I have entered through my Python Flask application, I am only able to get the first input, not the second. Here is how I am trying to retrieve the data.

@app.route('/div', methods=['POST'])
def div_post():
    scoreFixed = request.form.get('scoreGame')
    print(scoreFixed)

    return redirect('/')

Please help me figure out how to retrieve the input from both elements that have been created in the form.

CodePudding user response:

Every id can only exist once in a html document or form. You can set unique ids by using the for loop index in your template.

    {% for i in range(2) %}
        <input type="text" class="sFixed" id="scoreFixed_{{i}}">
    {% endfor %}

In your flask endpoint you can then access the scores like this

scores = []
for i in range(2):
    score = request.form.get(f"score_Fixed_{i}")
    scores.append(score)   

CodePudding user response:

First: you have to use name= instead of id= to get it in Flask
(and probably in other frameworks/languages you have to also use name instead of id).

Second: you can use getlist("scoreFixed") to get all elements with the same name.

Third: you need button to send it.


Minimal working example:

from flask import Flask, request, render_template_string

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    print('args :', request.args)
    print('form :', request.form)
    print('json :', request.json)
    print('files:', request.files)
    print('scoreFixed:', request.form.getlist("scoreFixed"))

    return render_template_string('''<form method="POST">
    {% for i in range(2) %}
        <input type="text" name="scoreFixed" ></br>
    {% endfor %}
<button type="submit">SEND</button>
</form>''')

if __name__ == '__main__':
    #app.debug = True 
    app.run()

Result for values a, b

args : ImmutableMultiDict([])
form : ImmutableMultiDict([('scoreFixed', 'a'), ('scoreFixed', 'b')])
json : None
files: ImmutableMultiDict([])
scoreFixed: ['a', 'b']

Of course you can use {{ i }} to add number to name to get every value separatelly

    {% for i in range(2) %}
        <input type="text" name="scoreFixed_{{ i }}" ></br>
    {% endfor %}
  • Related