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">

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

Here is the function on server.py that always return the first value

@app.route("/")
@app.route("/index")
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

controller.py

def get_coutries():
    con = get_connection()
    countries = []
    with con.cursor() as cursor:
        cursor.execute("select code, name, continent from country")
        countries = cursor.fetchall()
    con.close()
    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.

Answers:

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 stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x