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 skills (
id serial PRIMARY KEY,
skillname VARCHAR ( 150 ) NOT NULL
);
#app.py
from flask import Flask, render_template, request
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('/', methods=['GET', 'POST'])
def index():
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
message = ''
if request.method == 'POST':
skills = request.form.getlist('field[]')
for value in skills:
cur.execute("INSERT INTO skills (skillname) VALUES (%s)",[value])
conn.commit()
cur.close()
message = "Succesfully Register"
return render_template('index.html', message=message)
if __name__ == "__main__":
app.run(debug=True)
templates/index.html
//templates/index.html
<html>
<head>
<title>Add Remove Input Fields Dynamically with Python Flask jQuery and PostgreSQL Database</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<style>
.input-wrapper div {
margin-bottom: 10px;
}
.remove-input {
margin-top: 10px;
margin-left: 15px;
vertical-align: text-bottom;
}
.add-input {
margin-top: 10px;
margin-left: 10px;
vertical-align: text-bottom;
}
</style>
</head>
<body>
<div style="width:85%;padding:50px;">
<h2>Add Remove Input Fields Dynamically with Python Flask jQuery and PostgreSQL Database</h2>
{% if message %}
<div class="alert alert-success">{{message}}</div>
{% endif %}
<form method="POST">
<div class="input-wrapper">
<div>Programming Language : <br/>
<input type="text" name="field[]" value=""/>
<a href="javascript:void(0);" class="add-input" title="Add input"><img src="/static/img/add.png"/></a>
</div>
</div>
<input type="submit" name="cmdsubmit">
</form>
</div>
<script>
$(document).ready(function(){
var max_input_fields = 10;
var add_input = $('.add-input');
var input_wrapper = $('.input-wrapper');
var new_input = '<div><input type="text" name="field[]" value=""/><a href="javascript:void(0);" class="remove-input" title="Remove input"><img src="/static/img/remove.png"/></a></div>';
var add_input_count = 1;
$(add_input).click(function(){
if(add_input_count < max_input_fields){
add_input_count++;
$(input_wrapper).append(new_input);
}
});
$(input_wrapper).on('click', '.remove-input', function(e){
e.preventDefault();
$(this).parent('div').remove();
add_input_count--;
});
});
</script>
</body>
</html>
