Search code examples
pythonflaskjinja2

pass a value from html link to my function in flask


I want to pass a value from html link to my function in flask: the police man name has a button next to it if it is clicked i should take its id and send it to the python function here is the html code :

 <ul class="list-group">
{% for p in policemen %}
 <li class="list-group-item">{{ "  "~ p.rank ~"  "}}
    <div class="col-md-2 text-center"> 

        <a href='/deletepolice/{{p.id}}' class="btn btn-primary btn-lg" > 
    </div> Delete ? 
        </a>
</li> 

{% endfor %}

here is the python function :

@app.route('/deletepolice/<string:id>', methods=['GET','POST'])
def deletepolice(id):
 # Create cursor
    cur = mysql.connection.cursor()
   # Execute
    cur.execute("DELETE FROM police WHERE id = %s", [id])

# Commit to DB
    mysql.connection.commit()

#Close connection
    cur.close()

    flash('Police man deleted', 'success')

return redirect(url_for('policemen'))

Solution

  • This should work. At the moment though the render_template of your HTML is not shown. Make sure that you are correctly passing the id to your a tag. When clicked the current way you have your a tag setup should lead you to that route.

    Are you getting errors when you click the link? If so what are they?