article

Tuesday, July 13, 2021

Delete multiple records by selecting checkboxes using Python Flask with PostgreSQL

Delete multiple records by selecting checkboxes using Python Flask with PostgreSQL

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

CREATE TABLE contacts (
id serial PRIMARY KEY,
fullname VARCHAR ( 150 ) NOT NULL,
position VARCHAR ( 150 ) NOT NULL,
office VARCHAR ( 150 ) NOT NULL
);

INSERT INTO
    contacts(fullname, position, office)
VALUES
('Tiger Wood', 'Accountant', 'Tokyo'),
('Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London'),
('Jacob thompson', 'Junior Technical Author', 'San Francisco'),
('cylde Ednalan', 'Software Engineer', 'Olongapo'),
('Rhona Davidson', 'Software Engineer', 'San Francisco'),
('Quinn Flynn', 'Integration Specialist', 'New York'),
('Tiger Nixon', 'Software Engineer', 'London'),
('Airi Satou', 'Pre-Sales Support', 'New York'),
('Angelica Ramos', 'Sales Assistant', 'New York'),
('Ashton updated', 'Senior Javascript Developer', 'Olongapo'),
('Bradley Greer', 'Regional Director', 'San Francisco'),
('Brenden Wagner', 'Javascript Developer', 'San Francisco'),
('Brielle Williamson', 'Personnel Lead', 'Olongapo'),
('Bruno Nash', 'Customer Support', 'New York'),
('cairocoders', 'Sales Assistant', 'Sydney'),
('Zorita Serrano', 'Support Engineer', 'San Francisco'),
('Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco'),
('Sakura Yamamoto', 'Support Engineer', 'Tokyo'),
('Serge Baldwin', 'Data Coordinator', 'Singapore'),
('Shad Decker', 'Regional Director', 'Tokyo');
app.py
 
#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>

Related Post