article

Friday, July 2, 2021

Multiple Select option using Python Flask Jquery Ajax and PostgreSQL database

Multiple Select option using Python Flask Jquery Ajax and PostgreSQL database

Python Flask Multiple Select option using Bootstrap Select Plugin and Jquery Ajax PostgreSQL database

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

bootstrap select https://developer.snapappointments.com/bootstrap-select/examples/

CREATE TABLE programming (
id serial PRIMARY KEY,
title VARCHAR ( 150 ) NOT NULL
);

INSERT INTO
    programming(title)
VALUES
('Python Flask'),
('Python Django'),
('Express.js'),
('Laravel'),
('Spring'),
('Angular'),
('React'),
('Vue');

CREATE TABLE skills (
id serial PRIMARY KEY,
skillname VARCHAR ( 150 ) NOT NULL
);


app.py
#app.py
from flask import Flask, render_template, request, jsonify
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 index(): 
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute("SELECT * FROM programming ORDER BY id")
    programming = cur.fetchall()  
    return render_template('index.html', programming = programming)
 
@app.route("/ajax_add",methods=["POST","GET"])
def ajax_add():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        hidden_skills = request.form['hidden_skills']
        print(hidden_skills)     
        cur.execute("INSERT INTO skills (skillname) VALUES (%s)",[hidden_skills])
        conn.commit()       
        cur.close()
        msg = 'New record created successfully'  
    return jsonify(msg)
 
    
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Multiple Select option using Python Flask Jquery Ajax and PostgreSQL database</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>
</head>
<body>
<br /><br />
<div class="container">
   <br />
   <h2 align="center">Multiple Select option using Python Flask Jquery Ajax and PostgreSQL database</h2>
   <br />
    <div class="col-md-4" style="margin-left:200px;">
		<form method="post" id="multiple_select_form">
		<select name="skills" id="skills" class="form-control selectpicker" data-live-search="true" multiple>
			{% for row in programming %}
			<option value="{{row.title}}">{{row.title}}</option>
			{% endfor %}
		</select>
		<br /><br />
		<input type="hidden" name="hidden_skills" id="hidden_skills" />
		<input type="submit" name="submit" class="btn btn-info" value="Submit" />
		</form>
    <br />
   </div>
</div>
<script>
$(document).ready(function(){
    $('.selectpicker').selectpicker();
     
    $('#skills').change(function(){
      $('#hidden_skills').val($('#skills').val());
    });
     
    $('#multiple_select_form').on('submit', function(event){
		event.preventDefault();
		if($('#skills').val() != '')
		{
			var form_data = $(this).serialize();
			$.ajax({
				url:"/ajax_add",
				method:"POST",
				data:form_data,
				success:function(data)
				{
				//console.log(data);
				$('#hidden_skills').val('');
				$('.selectpicker').selectpicker('val', '');
				alert(data);
				}
			})
		}
		else
		{
			alert("Please select framework");
			return false;
		}
    });
});
</script>
</body>
</html>

Related Post