-3

I am new to HTML so having a bit of an issue with passing a value from HTML to python function. So what I am doing is making buttons with a loop, code is following:

Python Code for making buttons:

@app.route('/Ongoing', methods=['POST', 'GET'])
def Ongoing():
id = ['1', '2', '3', '4', '5', '6', '7', '8']
length = 8
return render_template('Run.html', length=length, id=id)

Html code for Buttons:

{% for i in range(length) %}
<form id="btn" action="{{ url_for('detail') }}" method="GET">
    <button type="submit" class="submit-btn-choice" style="margin-top: 20px;">Name</button>
</form>
{%endfor%}

Now I have 8 buttons. So what I want is when I press the first button first value of id which is 1 should be sent back to the called function(detail). In the same way when the second button is pressed value of 2 is sent back with it.

The function to which value is send is following:

@app.route('/detail', methods=['POST', 'GET'])
def detail(id):
response = Coup_data(id)
return render_template('detail.html', response =response )

I would really appreciate the help. Thanks

Masuk Helal Anik
  • 2,155
  • 21
  • 29
ZSA
  • 85
  • 1
  • 13

2 Answers2

0

Check out this response to a similar question. Basically, your form (when submitted) will send it's value (with a multipart/form-data MIME type), and then you can read the values in your API method.

That being said, your HTML <form> doesn't have any fields or <input> elements in it - so it's just going to send empty data to the backend on submission. It'll take some reworking, but you could update your API route to accept URL parameters, and then in your template, specify the id:

<form id="btn" action="{{ url_for('detail', id=id) }}" method="GET">

Your API URL would look like /detail?id=1

And then for your route, parse request.args (docs) for the id

wgd3
  • 141
  • 4
  • Thanks for reply, Although I have managed to solve the issue but I will try it for learning purposes. – ZSA Aug 27 '21 at 08:39
0

I have managed to solve the problem though don't know how efficient or bad the logic is. The changes that I have made are following:

Html code for Buttons:

Here I have used name and value property to identify pressed button and changed method to POST

{% for i in range(length) %}
<form id="btn" action="{{ url_for('detail') }}" method="POST">
   <button type="submit" class="submit-btn-choice" style="margin-top: 20px;" name="Val" value="{{id[i]}}">Name</button>
</form>
{%endfor%}

Called Function Code:

Here I am receiving posted value using request.form and use it for my function call.

@app.route('/detail', methods=['POST', 'GET'])
def detail():
if request.method == 'POST':
    id = request.form.get('Val')
response = Coup_data(id)
return render_template('detail.html', response =response )
ZSA
  • 85
  • 1
  • 13