How to send dynamically a value from HTML on Flask?

I am getting the values from a MySQL database and I can display it on the HTML, but when I try to send send a value I always get the first.

Here is the form:

<form action="/delete_country" method="post">

          {% for header in headers %}
          {% endfor %}
        {% for row in countries %}
          {% for cell in row %}
          {% endfor %}
          <td><input type="text" name="id_country" value="{{row[0]}}"></td>
          <td><button type="submit">Delete</button></td>
        {% endfor %}

Here is the function on that always return the first value

def index():
    headers = ("CODE", "Name", "Continent", "code2", "Delete")
    countries = controller.get_coutries()
    return render_template("index.html", headers=headers, countries=countries)

@app.route("/delete_country", methods=['POST'])
def delete_country():
    id_country = request.form['id_country']
    return id_country

def get_coutries():
    con = get_connection()
    countries = []
    with con.cursor() as cursor:
        cursor.execute("select code, name, continent from country")
        countries = cursor.fetchall()
    return countries

How to send dynamically a value from HTML on Flask?

If I click on Antartica, which code is ATA It’ll return ABW.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

<td><input type="text" name="id_country" value="{{row[0]}}"></td>

You Set in each loop the same id so you have a lot of this inputs with same ids and thats the reason why you get the first value

I prefer links for such things and not a form, and use url parameter on flask side.

<a href="http://yourip/delete_country/{{row[0]}}"></a>

@app.route("/delete_country/<id>", methods=['POST'])
def delete_country(id):
    id_country = id
    return id_country

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x