Home > Back-end >  How to send dynamically a value from HTML on Flask?
How to send dynamically a value from HTML on Flask?

Time:03-13

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

Countries screenshot

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

CodePudding user response:

<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
  • Related