Home > Mobile >  How to pass a variable to a flask app route through a html button
How to pass a variable to a flask app route through a html button

Time:10-05

I am trying to create a page where it shows records from the database and shows a delete button next to them. One of the elements shown is the variable needed for the delete function my problem is that I do not know how to get and pass that variable for the route that deletes the record from the database.

routes.py

@app.route("/deletetraining",methods=['GET', 'POST'])
def deleteTraining():
    return render_template('deleteTraining.html', trainings = getAllTrainings(), title = 'Delete')

@app.route("/delete")
def delete(tid):
    deleteTrainingByID(tid)
    return redirect(url_for('deleteTraining'))

deleteTraining.html

{% extends 'layout.html' %}
{% block content %}
<h1 >All Trainings</h1>
<table  >
    <thead>
        <tr>
            <th scope="col">TID</th>
            <th scope="col">Workplan</th>
            <th scope="col">Cost Centre Code</th>
            <th scope="col">Objective</th>
            <th scope="col">Name</th>
            <th scope="col">Location</th>
            <th scope="col">Start Date</th>
            <th scope="col">End Date</th>
            <th scope="col">Hours</th>
            <th scope="col">Days</th>
            <th scope="col">Gender Hours</th>
            <th scope="col">For MEL</th>
        </tr>
    </thead>
    <tbody>
        {% for training in trainings %}
            <tr>
                {% for element in training %}
                    <td>{{element}}</td>
                {% endfor %}
                <td>
                    <a  type="button" href="/delete">Delete</a>
                </td>
            </tr>
        {% endfor %}
    </tbody>
</table>
{% endblock content %}

CodePudding user response:

In the template you must pass the id in the delete training button

 <a  type="button" href="/delete/{{training.id}}">Delete</a>

And in your @app.route you must add

@app.route("/delete/<tid>")
  • Related