article

Wednesday, May 12, 2021

Python Flask PostgreSQL Delete Multiple records using checkbox with getlist

Python Flask PostgreSQL Delete Multiple records using checkbox with getlist

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

Crate database table
CREATE TABLE students (
id serial PRIMARY KEY,
fname VARCHAR ( 40 ) NOT NULL,
lname VARCHAR ( 40 ) NOT NULL,
email VARCHAR ( 40 ) NOT NULL
profile_pic VARCHAR ( 150 ) NULL
);

SELECT * FROM students 

Multiple insert
INSERT INTO
    students(id,fname,lname,email)
VALUES
    ('Quinn','Flynn'', 'Flynn'@gmail.com'),
    ('Tiger','nizon', 'nizon@gmail.com'),
    ('Airi','sato', 'sato@gmail.com');
app.py
 
#app.py
from flask import Flask, render_template, flash, redirect, url_for, request
import psycopg2 #pip install psycopg2 
import psycopg2.extras
 
app = Flask(__name__)
 
app.secret_key = "cairocoders-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 home():
    cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
    cursor.execute("SELECT * FROM students")
    rows = cursor.fetchall()
    return render_template('index.html', students=rows)

@app.route('/delete', methods=['GET', 'POST'])
def index():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

    if request.method == 'POST': 
        #test = request.form.getlist('mycheckbox')
        for getid in request.form.getlist('mycheckbox'):
            print(getid)
            cur.execute('DELETE FROM students WHERE id = {0}'.format(getid))
            conn.commit()
        flash('Student Removed Successfully')
        return redirect('/')

if __name__ == '__main__':
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Python Flask PostgreSQL Delete Multiple records using checkbox with getlist</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<div class="container">
 <div class="row">
        <div class="col-md-12">
        <p><h2>Python Flask PostgreSQL Delete Multiple records using checkbox with getlist</h2></p>
        <div class="table-responsive">
        <form method="POST" action="/delete">        
        <table id="mytable" class="table table-bordred table-striped">
            <thead>
                <th><input type="checkbox" id="checkall" /></th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email</th>
                <th width="50">Edit</th>
                <th width="50">Delete</th>
            </thead>
            <tbody>
            {% for rs in students %}
            <tr>
              <td><input type="checkbox" value="{{ rs.id }}" name="mycheckbox" class="checkthis" /></td>
              <td>{{ rs.fname }}</td>
              <td>{{ rs.lname }}</td>
              <td>{{ rs.email }}</td>
              <td><p data-placement="top" data-toggle="tooltip" title="Edit"><button class="btn btn-primary btn-xs" data-title="Edit" data-toggle="modal" data-target="#edit" ><span class="glyphicon glyphicon-pencil"></span></button></p></td>
              <td><p data-placement="top" data-toggle="tooltip" title="Delete"><button class="btn btn-danger btn-xs" data-title="Delete" data-toggle="modal" data-target="#delete" ><span class="glyphicon glyphicon-trash"></span></button></p></td>
            </tr>
            {% endfor %}
            </tbody>
         
      </table><input type="submit" value="Delete All Selected" class="btn btn-primary">  
      <br/>
      <div>
        {% with messages = get_flashed_messages() %}
            {% if messages %}
            {% for message in messages %}
            <div class="alert alert-danger" role="alert">{{ message }}</div>
            {% endfor %}
            {% endif %}
        {% endwith %}
        </div>
        </form>        
            </div>
             
        </div>
 </div>
</div>
<script>
$(document).ready(function(){
$("#mytable #checkall").click(function () {
        if ($("#mytable #checkall").is(':checked')) {
            $("#mytable input[type=checkbox]").each(function () {
                $(this).prop("checked", true);
            });
 
        } else {
            $("#mytable input[type=checkbox]").each(function () {
                $(this).prop("checked", false);
            });
        }
    });
     
    $("[data-toggle=tooltip]").tooltip();
});
</script>  
</body>
</html>

Related Post