问题
I have a form inside an html file, this form is creating new input fields in which the user is supposed to type some info. Later, i wanna pass all those values into my python main file (application.py)and do somethings with them. The problem is that i don't know how to pass several values into python. Normally i would use this
request.form.get("username")
which returns me the value of the input field named "username" inside my html file. Now, i have several input fields which are generated when the user pushes a button:
$("#add_dream").click(function(){
$("#"+x).append('<button type="submit" style="height:30px;" class="delete"
id="ix">Remove</button>')
document.getElementById("ix").setAttribute("id","delbuttdream"+j)
}
This is not the whole code, but it may help to understand what i'm saying. This new fields can be created an deleted as many times as the user wants to, so the name of the fields or their ids don't follow a straight order (1,2,3,4...). I wanna know if there's anyway in which i can call from python using request.form.get all the elements of the same clase or with certain id and not only one of them by name
回答1:
Example form:
Items in random order</br>
<form method="POST">
<input name="item4" value="val4"/></br>
<input name="item2" value="val2"/></br>
<input name="item1" value="val1"/></br>
<input name="item3" value="val3"/></br>
<button type="submit">OK</button>
</form>
request.form
behaves like dictionary and you can use request.form.items()
to get all keys and values and filter them.
for key, val in request.form.items():
#print(key,val)
if key.startswith("item"):
print(key, val)
or request.form.keys()
to get only keys to filter and sort them.
keys = request.form.keys()
keys = [key for key in keys if key.startswith("item")]
keys = sorted(keys)
for key in keys:
#print(key, request.form[key])
print(key, request.form.get(key))
Minimal working code:
from flask import Flask, request, render_template_string
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
print('--- original order ---')
for key, val in request.form.items():
if key.startswith("item"):
print(key, val)
print('--- sorted ---')
keys = request.form.keys()
keys = [key for key in keys if key.startswith("item")]
keys = sorted(keys)
for key in keys:
#print(key, request.form[key])
print(key, request.form.get(key))
return render_template_string('''Items in random order</br>
<form method="POST">
<input name="item4" value="val4"/></br>
<input name="item2" value="val2"/></br>
<input name="item1" value="val1"/></br>
<input name="item3" value="val3"/></br>
<button type="submit">OK</button>
</form>
''')
if __name__ == '__main__':
app.run(debug=
True)
来源:https://stackoverflow.com/questions/58160006/how-to-get-multiple-elements-from-a-form-using-request-form-get