Delete multiple records by selecting checkboxes using Python Flask with MySQLdb
app.py
#app.py
from flask import Flask, render_template, request, redirect, flash
from flask_mysqldb import MySQL,MySQLdb #pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb
app = Flask(__name__)
app.secret_key = "caircocoders-ednalan"
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'testingdb'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)
@app.route('/')
def main():
cursor = mysql.connection.cursor()
cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
result = cur.execute("SELECT * FROM contacts ORDER BY id")
contacts = cur.fetchall()
return render_template('index.html', contacts=contacts)
@app.route('/delete', methods=['GET', 'POST'])
def delete():
cursor = mysql.connection.cursor()
cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
if request.method == 'POST':
for getid in request.form.getlist('mycheckbox'):
print(getid)
cur.execute('DELETE FROM contacts WHERE id = {0}'.format(getid))
mysql.connection.commit()
flash('Successfully Deleted!')
return redirect('/')
if __name__ == '__main__':
app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Delete multiple records by selecting checkboxes using Python Flask with MySQLdb</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<br />
<h3 align="center">Delete multiple records by selecting checkboxes using Python Flask with MySQLdb</h3><br />
<form method="POST" action="/delete">
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th>Name</th>
<th>Phone</th>
<th>Email</th>
<th>Delete</th>
</tr>
{% for row in contacts %}
<tr id="{{row.id}}" >
<td>{{row.fullname}}</td>
<td>{{row.phone}}</td>
<td>{{row.email}}</td>
<td><input type="checkbox" name="mycheckbox" value="{{row.id}}" /></td>
</tr>
{% endfor %}
</table>
</div>
<div align="center">
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<div class="alert alert-danger" role="alert">{{ message }}</div>
{% endfor %}
{% endif %}
{% endwith %}
<input type="submit" value="Delete All Selected" class="btn btn-primary">
</div>
</form>
</body>
</html>
VIDEO