In this video we show you how to Delete multiple records by checking checkbox using Python Flask with PostgreSQL
Subscribe: https://www.youtube.com/c/Cairocoders/featured
Source Code
#app.py
from flask import Flask, render_template, request, redirect, flash
import psycopg2 #pip install psycopg2
import psycopg2.extras
app = Flask(__name__)
app.secret_key = "caircocoders-ednalan"
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)
@app.route('/')
def main():
cur = conn.cursor(cursor_factory=psycopg2.extras.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():
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
if request.method == 'POST':
for getid in request.form.getlist('mycheckbox'):
print(getid)
cur.execute('DELETE FROM contacts WHERE id = {0}'.format(getid))
conn.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 PostgreSQL</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 PostgreSQL</h3><br />
<form method="POST" action="/delete">
<div class="table-responsive">
<div align="right" style="padding:10px;">
{% 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>
<table class="table table-bordered">
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Delete</th>
</tr>
{% for row in contacts %}
<tr id="{{row.id}}" >
<td>{{row.fullname}}</td>
<td>{{row.position}}</td>
<td>{{row.office}}</td>
<td><input type="checkbox" name="mycheckbox" value="{{row.id}}" /></td>
</tr>
{% endfor %}
</table>
</div>
</form>
</body>
</html>
#python #postgresql