article

Saturday, July 10, 2021

Upload Multiple Images using Python Flask PostgreSQL Database

Upload Multiple Images using Python Flask 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

CREATE TABLE images (
id serial PRIMARY KEY,
file_name VARCHAR ( 100 ) NOT NULL,
uploaded_on TIMESTAMP
);
app.py
 
#app.py
from flask import Flask, render_template, redirect, request, flash
from werkzeug.utils import secure_filename
import os
#import magic
import urllib.request
from datetime import datetime
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)
 
UPLOAD_FOLDER = 'static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
  
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
  
def allowed_file(filename):
 return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
 
@app.route('/')
def index():
    return render_template('index.html')
 
@app.route("/upload",methods=["POST","GET"])
def upload():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    now = datetime.now()
    print(now)
    if request.method == 'POST':
        files = request.files.getlist('files[]')
        #print(files)
        for file in files:
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                cur.execute("INSERT INTO images (file_name, uploaded_on) VALUES (%s, %s)",[filename, now])
                conn.commit()
            print(file)
        cur.close()   
        flash('File(s) successfully uploaded')    
    return redirect('/')
    
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
 <title>Upload Multiple Images using Python Flask PostgreSQL Database</title>
<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>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h2>Upload Multiple Images using Python Flask PostgreSQL Database</h2>
    <div class="row">
        <div class="col-lg-12">
            <p>
                {% with messages = get_flashed_messages() %}
                  {% if messages %}
                 {% for message in messages %}
                   <div class="alert alert-success">
                    <strong>{{ message }}</strong>
                  </div>
                 {% endfor %}
                  {% endif %}
                {% endwith %}
               </p>
  <div>
   <!-- File upload form -->
   <form method="post" action="/upload" enctype="multipart/form-data" class="form-inline">
    <div class="form-group">
                      <label>Choose Images: </label>
                      <input type="file" name="files[]" id="fileInput" class="form-control" multiple >
                 </div>
                 <input type="submit" name="submit" class="btn btn-success" value="UPLOAD"/>
             </form>
  </div>
  </div>
 </div>
</div>
<script>
$(document).ready(function(){
 // File type validation
    $("#fileInput").change(function(){
        var fileLength = this.files.length;
        var match= ["image/jpeg","image/png","image/jpg","image/gif"];
        var i;
        for(i = 0; i < fileLength; i++){ 
            var file = this.files[i];
            var imagefile = file.type;
            if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2]) || (imagefile==match[3]))){
                alert('Please select a valid image file (JPEG/JPG/PNG/GIF).');
                $("#fileInput").val('');
                return false;
            }
        }
    });
});
</script>
</body>
</html>

Wednesday, July 7, 2021

Add Edit Delete Datatable Row Using Jquery Ajax Python Flask and PostgreSQL database

Add Edit Delete Datatable Row Using Jquery Ajax Python Flask and 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

CREATE TABLE employee (
id serial PRIMARY KEY,
name VARCHAR ( 100 ) NOT NULL,
position VARCHAR ( 100 ) NOT NULL,
office VARCHAR ( 100 ) NOT NULL
);

INSERT INTO
    employee(name, 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');
app.py
#app.py
from flask import Flask, render_template, redirect, request, flash, 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 employee ORDER BY id")
    employee = cur.fetchall()
    return render_template('index.html', employee=employee)
 
@app.route("/ajax_add",methods=["POST","GET"])
def ajax_add():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        txtname = request.form['txtname']
        txtposition = request.form['txtposition']
        txtoffice = request.form['txtoffice']
        print(txtname)
        if txtname == '':
            msg = 'Please Input name'  
        elif txtposition == '':
           msg = 'Please Input Position'  
        elif txtoffice == '':
           msg = 'Please Input Office'  
        else:        
            cur.execute("INSERT INTO employee (name,position,office) VALUES (%s,%s,%s)",[txtname,txtposition,txtoffice])
            conn.commit()       
            cur.close()
            msg = 'New record created successfully'   
    return jsonify(msg)
 
@app.route("/ajax_update",methods=["POST","GET"])
def ajax_update():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        string = request.form['string']
        txtname = request.form['txtname']
        txtposition = request.form['txtposition']
        txtoffice = request.form['txtoffice']
        print(string)
        cur.execute("UPDATE employee SET name = %s, position = %s, office = %s WHERE id = %s ", [txtname, txtposition, txtoffice, string])
        conn.commit()       
        cur.close()
        msg = 'Record successfully Updated'   
    return jsonify(msg)    
 
@app.route("/ajax_delete",methods=["POST","GET"])
def ajax_delete():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        getid = request.form['string']
        print(getid)
        cur.execute('DELETE FROM employee WHERE id = {0}'.format(getid))
        conn.commit()       
        cur.close()
        msg = 'Record deleted successfully'   
    return jsonify(msg) 

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Add Edit Delete Datatable Row Using Jquery Ajax Python Flask and PostgreSQL database</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip();
    var actions = $("table td:last-child").html();
    // Append table with add row form on add new button click
    $(".add-new").click(function(){
        $(this).attr("disabled", "disabled");
        var index = $("table tbody tr:last-child").index();
        var row = '<tr>' +
            '<td><input type="text" class="form-control" name="name" id="txtname"></td>' +
            '<td><input type="text" class="form-control" name="position" id="txtposition"></td>' +
            '<td><input type="text" class="form-control" name="office" id="txtoffice"></td>' +
        '<td>' + actions + '</td>' +
        '</tr>';
        $("table").append(row);  
        $("table tbody tr").eq(index + 1).find(".add, .edit, .delete").toggle();
        $('[data-toggle="tooltip"]').tooltip();
 
    });
   
    // Add row on add button click
    $(document).on("click", ".add", function(){
        var empty = false;
        var input = $(this).parents("tr").find('input[type="text"]');
        input.each(function(){
            if(!$(this).val()){
                $(this).addClass("error");
                empty = true;
            } else{
                $(this).removeClass("error");
            }
        });
        var txtname = $("#txtname").val();
        var txtposition = $("#txtposition").val();
        var txtoffice = $("#txtoffice").val();
        $.post("/ajax_add", { txtname: txtname, txtposition: txtposition, txtoffice: txtoffice}, function(data) {
            $("#displaymessage").html(data);
            $("#displaymessage").show();
        });
        $(this).parents("tr").find(".error").first().focus();
        if(!empty){
            input.each(function(){
                $(this).parent("td").html($(this).val());
            });   
            $(this).parents("tr").find(".add, .edit, .delete").toggle();
            $(".add-new").removeAttr("disabled");
        } 
    });
    // Delete row on delete button click
    $(document).on("click", ".delete", function(){
        $(this).parents("tr").remove();
        $(".add-new").removeAttr("disabled");
        var id = $(this).attr("id");
        var string = id;
        $.post("/ajax_delete", { string: string}, function(data) {
            $("#displaymessage").html(data);
            $("#displaymessage").show();
        });
    });
    // update rec row on edit button click
    $(document).on("click", ".update", function(){
        var id = $(this).attr("id");
        var string = id;
        var txtname = $("#txtname").val();
        var txtposition = $("#txtposition").val();
        var txtoffice = $("#txtoffice").val();
        $.post("/ajax_update", { string: string,txtname: txtname, txtposition: txtposition, txtoffice: txtoffice}, function(data) {
            $("#displaymessage").html(data);
            $("#displaymessage").show();
        });
         
         
    });
    // Edit row on edit button click
    $(document).on("click", ".edit", function(){  
        $(this).parents("tr").find("td:not(:last-child)").each(function(i){
            if (i=='0'){
                var idname = 'txtname';
            }else if (i=='1'){
                var idname = 'txtposition';
            }else if (i=='2'){
                var idname = 'txtoffice';
            }else{} 
            $(this).html('<input type="text" name="updaterec" id="' + idname + '" class="form-control" value="' + $(this).text() + '">');
        });  
        $(this).parents("tr").find(".add, .edit").toggle();
        $(".add-new").attr("disabled", "disabled");
        $(this).parents("tr").find(".add").removeClass("add").addClass("update"); 
    });
});
</script> 
</head>
<body>
    <div class="container"><p><h1 align="center">Add Edit Delete Datatable Row Using Jquery Ajax Python Flask and PostgreSQL database</h1></p>
        <div class="table-wrapper">
            <div class="table-title">
                <div class="row">
                    <div class="col-sm-8"><h2>Employee <b>Details</b></h2></div>
                    <div class="col-sm-4">
                        <button type="button" class="btn btn-info add-new"><i class="fa fa-plus"></i> Add New</button>
                    </div>
                    <div class='btn btn-info' id="displaymessage" style="display:none;width:100%;margin-top:10px;"></div>
                </div>
            </div>
   <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Position</th>
                        <th>Office</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    {% for row in employee %}    
                    <tr>
                        <td>{{row.name}}</td>
                        <td>{{row.position}}</td>
                        <td>{{row.office}}</td>
                        <td>
                            <a class="add" title="Add" data-toggle="tooltip" id="{{row.id}}"><i class="fa fa-user-plus"></i></a>
                            <a class="edit" title="Edit" data-toggle="tooltip" id="{{row.id}}"><i class="fa fa-pencil"></i></a>
                            <a class="delete" title="Delete" data-toggle="tooltip" id="{{row.id}}"><i class="fa fa-trash-o"></i></a>
                        </td>
                    </tr>   
                    {% endfor %}    
                </tbody>
            </table>
        </div>
    </div>     
<style type="text/css">
    body {
        color: #404E67;
        background: #F5F7FA;
  font-family: 'Open Sans', sans-serif;
 }
 .table-wrapper {
  width: 700px;
  margin: 30px auto;
        background: #fff;
        padding: 20px; 
        box-shadow: 0 1px 1px rgba(0,0,0,.05);
    }
    .table-title {
        padding-bottom: 10px;
        margin: 0 0 10px;
    }
    .table-title h2 {
        margin: 6px 0 0;
        font-size: 22px;
    }
    .table-title .add-new {
        float: right;
  height: 30px;
  font-weight: bold;
  font-size: 12px;
  text-shadow: none;
  min-width: 100px;
  border-radius: 50px;
  line-height: 13px;
    }
 .table-title .add-new i {
  margin-right: 4px;
 }
    table.table {
        table-layout: fixed;
    }
    table.table tr th, table.table tr td {
        border-color: #e9e9e9;
    }
    table.table th i {
        font-size: 13px;
        margin: 0 5px;
        cursor: pointer;
    }
    table.table th:last-child {
        width: 100px;
    }
    table.table td a {
  cursor: pointer;
        display: inline-block;
        margin: 0 5px;
  min-width: 24px;
    }   
 table.table td a.add {
        color: #27C46B;
    }
    table.table td a.edit {
        color: #FFC107;
    }
    table.table td a.delete {
        color: #E34724;
    }
    table.table td i {
        font-size: 19px;
    }
 table.table td a.add i {
        font-size: 24px;
     margin-right: -1px;
        position: relative;
        top: 3px;
    }    
    table.table .form-control {
        height: 32px;
        line-height: 32px;
        box-shadow: none;
        border-radius: 2px;
    }
 table.table .form-control.error {
  border-color: #f50000;
 }
 table.table td .add {
  display: none;
 }
</style>    
</body>
</html>

Search Box SQL LIKE operator using Jquery Ajax Python Flask and PostgreSQL database

Search Box SQL LIKE operator using Jquery Ajax Python Flask and 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

CREATE TABLE employee (
id serial PRIMARY KEY,
name VARCHAR ( 100 ) NOT NULL,
position VARCHAR ( 100 ) NOT NULL,
office VARCHAR ( 100 ) NOT NULL,
age INT NOT NULL,
salary INT NOT NULL,
photo VARCHAR ( 150 ) NOT NULL
);

INSERT INTO
    employee(name, position, office, age, salary, photo)
VALUES
('Tiger Wood', 'Accountant', 'Tokyo', 36, 5689, '01.jpg'),
('Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, 5648, '02.jpg'),
('Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, 5689, '03.jpg'),
('cylde Ednalan', 'Software Engineer', 'Olongapo', 23, 54654, '04.jpg'),
('Rhona Davidson', 'Software Engineer', 'San Francisco', 26, 5465, '05.jpg'),
('Quinn Flynn', 'Integration Specialist', 'New York', 53, 56465, '06.jpg'),
('Tiger Nixon', 'Software Engineer', 'London', 45, 456, '07.jpg'),
('Airi Satou', 'Pre-Sales Support', 'New York', 25, 4568, '08.jpg'),
('Angelica Ramos', 'Sales Assistant', 'New York', 45, 456, '09.jpg'),
('Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, 54565, '01.jpg'),
('Bradley Greer', 'Regional Director', 'San Francisco', 27, 5485, '02.jpg'),
('Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, 65468, '03.jpg'),
('Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, 354685, '04.jpg'),
('Bruno Nash', 'Customer Support', 'New York', 36, 65465, '05.jpg'),
('cairocoders', 'Sales Assistant', 'Sydney', 45, 56465, '06.jpg'),
('Zorita Serrano', 'Support Engineer', 'San Francisco', 38, 6548, '07.jpg'),
('Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, 545, '08.jpg'),
('Sakura Yamamoto', 'Support Engineer', 'Tokyo', 48, 5468, '05.jpg'),
('Serge Baldwin', 'Data Coordinator', 'Singapore', 85, 5646, '05.jpg'),
('Shad Decker', 'Regional Director', 'Tokyo', 45, 4545, '05.jpg');
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():
    return render_template('index.html')
 
@app.route("/searchdata",methods=["POST","GET"])
def searchdata():
    if request.method == 'POST':
        search_word = request.form['search_word']
        print(search_word)
        cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
        cur.execute('SELECT * FROM employee WHERE name LIKE %(name)s', { 'name': '%{}%'.format(search_word)})
        employee = cur.fetchall()
    return jsonify({'data': render_template('response.html', employee=employee)})
 
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Search Box SQL LIKE operator using Jquery Ajax Python Flask and PostgreSQL database</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
  $(".search_button").click(function() {
      var search_word = $("#search_box").val();
      var dataString = 'search_word='+ search_word;
      if(search_word==''){
      }else{
        $.ajax({
          type: "POST",
          url: "/searchdata",
          data: dataString,
          cache: false,
          beforeSend: function(html) {
              document.getElementById("insert_search").innerHTML = ''; 
              $("#flash").show();
              $("#searchword").show();
              $(".searchword").html(search_word);
              $("#flash").html('<img src="/static/img/loader.gif" align="absmiddle"> Loading Results...');
            },
          success: function(html){
              $("#insert_search").show();
              $("#insert_search").append(html.data);
              $("#flash").hide();
          }
        });
      }
    return false;
  });
});
</script>
</head>
<body>
<div align="center">
  <div style="width:700px">
  <div style="margin-top:20px; text-align:left">
    <p align="center"><h1>Search Box SQL LIKE operator using Jquery Ajax Python Flask and PostgreSQL database </h1></p>
    <form method="get" action="">
    <input type="text" name="search" id="search_box" class='search_box'/>
    <input type="submit" value="Search" class="search_button" /><br />
    <span style="color:#666666; font-size:14px; font-family:Arial, Helvetica, sans-serif;"><b>Ex :</b> Cairocoders</span>
    </form>
  </div>   
  <div>
    <div id="searchword">Search results for <span class="searchword"></span></div>
    <div id="flash"></div>
    <ol id="insert_search" class="update"></ol>
  </div>
  </div>
</div>
<style>
body{
font-family:Arial, Helvetica, sans-serif;
}
a
{
color:#DF3D82;
text-decoration:none
}
a:hover
{
color:#DF3D82;
text-decoration:underline;
}
#search_box{
 padding:3px; border:solid 1px #666666; width:400px; height:45px; font-size:18px;-moz-border-radius: 6px;-webkit-border-radius: 6px;
}
.search_button{
 height:50px;border:#fe6f41 solid 1px; padding-left:9px;padding-right:9px;padding-top:9px;padding-bottom:9px; color:#000; font-weight:bold; font-size:16px;-moz-border-radius: 6px;-webkit-border-radius: 6px;
}
ol.update{
 list-style:none;font-size:1.1em; margin-top:20px;padding-left:0; 
}
#flash{
 margin-top:20px;
 text-align:left;
}
#searchword{
 text-align:left; margin-top:20px; display:none;
 font-family:Arial, Helvetica, sans-serif;
 font-size:16px;
 color:#000;
}
.searchword{
 font-weight:bold;
 color:#fe6f41;
}
ol.update li{ border-bottom:#dedede dashed 1px; text-align:left;padding-top:10px;padding-bottom:10px;}
ol.update li:first-child{ border-top:#dedede dashed 1px; text-align:left}
</style>
</body>
</html>
templates/response.html
//templates/response.html
{% for row in employee %}  
  <li>{{row.name}} <br/><span style='font-size:12px;'>{{row.position}}</span></li>
{% endfor %}

Tuesday, July 6, 2021

Live Data Search using Jquery Ajax Python Flask and PostgreSQL Database

Live Data Search using Jquery Ajax Python Flask and 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

CREATE TABLE employee (
id serial PRIMARY KEY,
name VARCHAR ( 100 ) NOT NULL,
position VARCHAR ( 100 ) NOT NULL,
office VARCHAR ( 100 ) NOT NULL,
age INT NOT NULL,
salary INT NOT NULL,
photo VARCHAR ( 150 ) NOT NULL
);

INSERT INTO
    employee(name, position, office, age, salary, photo)
VALUES
('Tiger Wood', 'Accountant', 'Tokyo', 36, 5689, '01.jpg'),
('Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, 5648, '02.jpg'),
('Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, 5689, '03.jpg'),
('cylde Ednalan', 'Software Engineer', 'Olongapo', 23, 54654, '04.jpg'),
('Rhona Davidson', 'Software Engineer', 'San Francisco', 26, 5465, '05.jpg'),
('Quinn Flynn', 'Integration Specialist', 'New York', 53, 56465, '06.jpg'),
('Tiger Nixon', 'Software Engineer', 'London', 45, 456, '07.jpg'),
('Airi Satou', 'Pre-Sales Support', 'New York', 25, 4568, '08.jpg'),
('Angelica Ramos', 'Sales Assistant', 'New York', 45, 456, '09.jpg'),
('Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, 54565, '01.jpg'),
('Bradley Greer', 'Regional Director', 'San Francisco', 27, 5485, '02.jpg'),
('Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, 65468, '03.jpg'),
('Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, 354685, '04.jpg'),
('Bruno Nash', 'Customer Support', 'New York', 36, 65465, '05.jpg'),
('cairocoders', 'Sales Assistant', 'Sydney', 45, 56465, '06.jpg'),
('Zorita Serrano', 'Support Engineer', 'San Francisco', 38, 6548, '07.jpg'),
('Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, 545, '08.jpg'),
('Sakura Yamamoto', 'Support Engineer', 'Tokyo', 48, 5468, '05.jpg'),
('Serge Baldwin', 'Data Coordinator', 'Singapore', 85, 5646, '05.jpg'),
('Shad Decker', 'Regional Director', 'Tokyo', 45, 4545, '05.jpg');
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():
    return render_template('index.html')
 
@app.route("/ajaxlivesearch",methods=["POST","GET"])
def ajaxlivesearch():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        search_word = request.form['query']
        print(search_word)
        if search_word == '':
            query = "SELECT * from employee ORDER BY id"
            cur.execute(query)
            employee = cur.fetchall()
        else:    
            cur.execute('SELECT * FROM employee WHERE name LIKE %(name)s', { 'name': '%{}%'.format(search_word)})
            numrows = int(cur.rowcount)
            employee = cur.fetchall()
            print(numrows)
    return jsonify({'htmlresponse': render_template('response.html', employee=employee, numrows=numrows)})
    
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Live Data Search using Jquery Ajax Python Flask and PostgreSQL Database</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  load_data();
  function load_data(query)
  {
   $.ajax({
    url:"/ajaxlivesearch",
    method:"POST",
    data:{query:query},
    success:function(data)
    {
      $('#result').html(data);
      $("#result").append(data.htmlresponse);
    }
   });
  }
  $('#search_text').keyup(function(){
    var search = $(this).val();
    if(search != ''){
    load_data(search);
   }else{
    load_data();
   }
  });
});
</script>
</head>
<body>
<div class="container search-table">
<p><h2 align="center">Live Data Search using Jquery Ajax Python Flask and PostgreSQL Database</h2></p>
            <div class="search-box">
                <div class="row">
                    <div class="col-md-3">
                        <h5>Search Field Name</h5>
                    </div>
                    <div class="col-md-9">
                        <input type="text" name="search_text" id="search_text" class="form-control" placeholder="Search fields e.g. Cairocoder">
                    </div> 
                </div>
            </div>
   <div id="result"></div>
</div>
<style>
.search-table{
    padding: 10%;
    margin-top: -6%;
}
.search-box{
    background: #c1c1c1;
    border: 1px solid #ababab;
    padding: 3%;
}
.search-box input:focus{
    box-shadow:none;
    border:2px solid #eeeeee;
}
.search-list{
    background: #fff;
    border: 1px solid #ababab;
    border-top: none;
}
.search-list h3{
    background: #eee;
    padding: 3%;color:#fe6f41;
    margin-bottom: 0%;
}
</style>
</body>
</html>
templates/response.html
//templates/response.html
<h3>{{numrows}} Records Found</h3>
<table class="table table-striped custab">
  <thead>
      <tr>
         <th>Name</th>
         <th>Position</th>
         <th>Office</th>
      </tr>
  </thead>
  <tbody>
{% for row in employee %}  
   <tr>
    <td>{{row.name}}</td>
    <td>{{row.position}}</td>
    <td>{{row.office}}</td>
   </tr>
{% endfor %}

SwiftUI Check Network Connection

SwiftUI Check Network Connection
ContentView.swift
 
//
//  ContentView.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    @ObservedObject var monitor = NetworkMonitor()
    @State private var showAlertSheet = false
    
    var body: some View {
        VStack {
            Image(systemName: monitor.isConnected ? "wifi" : "wifi.slash")
                .font(.system(size: 56))
            Text(monitor.isConnected ? "Connected!" : "Not connected!")
                .padding()
            Button("Perform Network Request") {
                self.showAlertSheet = true
            }
        }
        .alert(isPresented: $showAlertSheet, content: {
            if monitor.isConnected {
                return Alert(title: Text("Success!"), message: Text("The network request can be performed"), dismissButton: .default(Text("OK")))
            }
            return Alert(title: Text("No Internet Connection"), message: Text("Please enable Wifi or Celluar data"), dismissButton: .default(Text("Cancel")))
        })
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
NetworkMonitor.swift
 
//
//  NetworkMonitor.swift
//  Test
//
//  Created by Cairocoders
//

import Foundation
import Network

final class NetworkMonitor: ObservableObject {
    let monitor = NWPathMonitor()
    let queue = DispatchQueue(label: "Monitor")
    
    @Published var isConnected = true
    
    init() {
        monitor.pathUpdateHandler =  { [weak self] path in
            DispatchQueue.main.async {
                self?.isConnected = path.status == .satisfied ? true : false
            }
        }
        monitor.start(queue: queue)
    }
}

Monday, July 5, 2021

SwiftUI Horizontal and Vertical Paging using TabView

SwiftUI Horizontal and Vertical Paging using TabView
ContentView.swift
 
//
//  ContentView.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI


struct ContentView: View {

    var body: some View {
        GeometryReader { proxy in
            TabView {
                ForEach(data){profilepic in
                    Image(profilepic.image)
                        .resizable()
                        .clipped()
                }
                .frame(
                    width: proxy.size.width,
                    height: proxy.size.height
                )
            }
            .tabViewStyle(PageTabViewStyle())
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

ContentView.swift
 
//
//  ContentView.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI


struct ContentView: View {

    var body: some View {
        GeometryReader { proxy in
            TabView {
                ForEach(data){profilepic in
                    Image(profilepic.image)
                        .resizable()
                        .clipped()
                }
                .rotationEffect(.degrees(-90)) // Rotate content
                .frame(
                    width: proxy.size.width,
                    height: proxy.size.height
                )
            }
            .frame(
                width: proxy.size.height, // Height & width swap
                height: proxy.size.width
            )
            .rotationEffect(.degrees(90), anchor: .topLeading) // Rotate TabView
            .offset(x: proxy.size.width) // Offset back into screens bounds
            .tabViewStyle(
                PageTabViewStyle(indexDisplayMode: .never)
            )
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
Model.swift
 
//
//  Model.swift
//  Test
//
//  Created by Cairocoders
//

import Foundation
struct Profile : Identifiable {
     
    var id : Int
    var name : String
    var image : String
}
 
var data = [
 
    Profile(id: 0, name: "Photo1", image: "photo1"),
    Profile(id: 1, name: "Photo2", image: "photo2"),
    Profile(id: 2, name: "Photo3", image: "photo3"),
    Profile(id: 3, name: "Photo4", image: "photo4"),
    Profile(id: 4, name: "Photo5", image: "photo5"),
]

Dynamic Loading of ComboBox using jQuery Ajax Python Flask and PostgreSQL



Dynamic Loading of ComboBox using jQuery Ajax Python Flask and 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

INSERT INTO
    carbrands(brand_name)
VALUES
('Toyota'),
('Honda'),
('Suzuki'),
('Mitsubishi'),
('Hyundai');

CREATE TABLE carmodels (
model_id serial PRIMARY KEY,
brand_id INT NOT NULL,
car_models VARCHAR ( 150 ) NOT NULL
);

INSERT INTO
    carmodels(brand_id,car_models)
VALUES
(1, 'Toyota Corolla'),
(2, 'Toyota Camry'),
(1, 'Toyota Yaris'),
(1, 'Toyota Sienna'),
(1, 'Toyota RAV4'),
(1, 'Toyota Highlander'),
(2, 'Honda HR-V'),
(2, 'Honda Odyssey'),
(3, 'Swift'),
(3, 'Celerio'),
(3, 'Ertiga'),
(3, 'Vitara'),
(4, 'Mirage'),
(4, 'Mirage G4'),
(4, 'Xpander Cross'),
(4, 'Montero Sport'),
(4, 'Strada Athlete'),
(5, 'Reina '),
(5, 'Accent'),
(5, 'Elantra'),
(5, 'Tucson');
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 carbrands ORDER BY brand_id")
    carbrands = cur.fetchall() 
    return render_template('index.html', carbrands=carbrands)
 
@app.route("/get_child_categories",methods=["POST","GET"])
def get_child_categories():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)    
    if request.method == 'POST':
        parent_id = request.form['parent_id']
        print(parent_id)
        cur.execute("SELECT * FROM carmodels WHERE brand_id = %s", [parent_id])
        carmodels = cur.fetchall()
    return jsonify({'htmlresponse': render_template('response.html', carmodels=carmodels)})

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Loading of ComboBox using jQuery Ajax Python Flask and PostgreSQL</title>
<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>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
 $('#search_category_id').change(function(){
    $.post("/get_child_categories", {
     parent_id: $('#search_category_id').val(),
    }, function(response){ 
        $('#show_sub_categories').html(response);
        $('#show_sub_categories').append(response.htmlresponse);
    });
    return false;
  });
}); 
</script>
</head>
<body>
  <div class="container">
    <div class="row">
      <div class="col-lg-2"></div>
    <div class="col-lg-8">
    <h3 align="center">Dynamic Loading of ComboBox using jQuery Ajax Python Flask and PostgreSQL</h3>
    <form action="#" name="form" id="form" method="post">
      <div class="form-group">
        <label>Select Category</label>
        <select name="search_category"  id="search_category_id" class="form-control">
          <option value="" selected="selected"></option>
          {% for row in carbrands %}
          <option value='{{row.brand_id}}'>{{row.brand_name}}</option>
          {% endfor %}
          </select> 
      </div>
      <div id="show_sub_categories"></div>
      <button type="submit" class="btn btn-primary">Submit</button>
    </form>
    </div>
    <div class="col-lg-2"></div>
  </div>
</div>
</body>
</html>
templates/response.html
//templates/response.html
<div class="form-group">
    <label>Select Sub Category</label>
    <select name="sub_category"  id="sub_category_id" class="form-control">
       <option value="" selected="selected"></option>
        {% for row in carmodels %} 
        <option value="{{row.model_id}}">{{row.car_models}}</option>
        {% endfor %}
    </select> 
</div>

Table Edit using jquery ajax Python Flask and PostgreSQL Database

Table Edit using jquery ajax Python Flask and 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

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');
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 ASC")
    topphpframework = cur.fetchall() 
    return render_template('index.html', topphpframework=topphpframework)
     
@app.route("/ajax",methods=["POST","GET"])
def ajax():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)    
    if request.method == 'POST':
        getid = request.form['id']
        getname = request.form['name']
        print(getid)
        cur.execute("UPDATE programming SET title = %s WHERE id = %s ", [getname, getid])
        conn.commit()       
        cur.close()
    return jsonify('Record updated successfully')

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Table Edit using jquery ajax Python Flask and PostgreSQL Database</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
  $(".edit_tr").click(function() {
    var ID=$(this).attr('id');
    $("#first_"+ID).hide();
    $("#first_input_"+ID).show();
  }).change(function(){
      var ID=$(this).attr('id');
      var first=$("#first_input_"+ID).val();
      var dataString = 'id='+ ID +'&name='+first;
      $("#first_"+ID).html('<img src="/staticf/img/loader.gif" />');
      if(first.length>0){
        $.ajax({
          type: "POST",
          url: "/ajax",
          data: dataString,
          cache: false,
          success: function(html)
          {
            $("#first_"+ID).html(first);
          }
        });
      }else{
        alert('Enter something.');
      }
  });
    
  $(".editbox").mouseup(function() {
   return false
  });
  $(document).mouseup(function() {
      $(".editbox").hide();
      $(".text").show();
  });
});
</script>
</head>
<body>
<center><p><h1>Table Edit using jquery ajax Python Flask and PostgreSQL Database</h1></p></center>
<div style="margin:0 auto; width:350px; padding:10px; background-color:#fff;"> 
<table width="100%" border="0">
  <tr class="head">
  <th>Frameworks</th>
  </tr>
  {% for row in topphpframework %}
      <tr id="{{row.id}}" bgcolor="#f2f2f2" class="edit_tr">
        <td width="50%" class="edit_td">
        <span id="first_{{row.id}}" class="text">{{row.title}}</span>
        <input type="text" name="name" value="{{row.title}}" class="editbox" id="first_input_{{row.id}}" />
        </td>
      </tr>
    {% endfor %}
</table>
</div>
<style>
  body
  {
  font-family:Arial, Helvetica, sans-serif;
  font-size:16px;
  }
  .head
  {
  background-color:#333;
  color:#FFFFFF
  }
  .edit_tr:hover
  {
  background:url(/static/img/edit.png) right no-repeat #80C8E5;
  cursor:pointer;
  }
  .editbox
  {
  display:none
  }
  .editbox
  {
  font-size:16px;
  width:270px;
  background-color:#ffffcc;
  border:solid 1px #000;
  padding:4px;
  }
  td
  {
  padding:10px;
  }
  th
  {
  font-weight:bold;
  text-align:left;
  padding:4px;
  }
  </style>
</body>
</html>

SwiftUI Simple Transition opacity slide and scale

SwiftUI Simple Transition opacity slide and scale ContentView.swift
 
//
//  ContentView.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State private var show = false
    
    var body: some View {
        
        VStack {
            Spacer()
        
            if show {
                LabelView()
                    .animation(.easeInOut(duration: 1.0))
                    //.transition(.opacity)
                    //.transition(AnyTransition.opacity.combined(with: .slide))
                    .transition(.asymmetric(insertion: AnyTransition.opacity.combined(with: .slide), removal: .scale))
            }
            
            Spacer()
            
            Button("Animate") {
                self.show.toggle()
            }.padding(20)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct LabelView: View {
    var body: some View {
        Text("Animate Button")
            .padding(10)
            .font(.title)
            .foregroundColor(.white)
            .background(RoundedRectangle(cornerRadius: 8).fill(Color.green).shadow(color: .gray, radius: 3))
    }
}

Sunday, July 4, 2021

Dynamic Drag and Drop Order List With jQuery Ajax and Python Flask PostgreSQL Database

Dynamic Drag and Drop Order List With jQuery Ajax and Python Flask 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

CREATE TABLE dragdrop (
id serial PRIMARY KEY,
text VARCHAR ( 150 ) NOT NULL,
listorder INT NOT NULL
);

INSERT INTO
    dragdrop(text,listorder)
VALUES
('Ajax', 3),
('Jquery', 5),
('PHP', 6),
('Mysqli', 7),
('Javascript', 1),
('Java', 4),
('Python', 2);

jqueryui sortable https://jqueryui.com/sortable/
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 dragdrop ORDER BY listorder ASC")
    dragdrop = cur.fetchall() 
    return render_template('index.html', dragdrop=dragdrop)
 
@app.route("/updateList",methods=["POST","GET"])
def updateList():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        cur.execute("SELECT * FROM dragdrop")    
        number_of_rows = cur.rowcount      
        getorder = request.form['order']    
        print(getorder)
        order = getorder.split(",", number_of_rows)
        print(order)
        count=0   
        for value in order:
            count +=1
            print(count)                       
            cur.execute("UPDATE dragdrop SET listorder = %s WHERE id = %s ", [count, value])
            conn.commit()       
        cur.close()
    return jsonify('Successfully Updated')
 
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Drag and Drop Order List With jQuery Ajax and Python Flask PostgreSQL Database</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function(){  
   function slideout(){
    setTimeout(function(){
      $("#response").slideUp("slow", function () {
    });
    }, 2000);
  }
   
  $("#response").hide();
  $(function() {
    $("#list ul").sortable({ opacity: 0.8, cursor: 'move', update: function() {
      var item_order = new Array();
      $('ul.reorder li').each(function() {
          item_order.push($(this).attr("id"));
      }); 
      var order_string = 'order='+item_order;
      $.ajax({
        method: "POST",
        url: "/updateList",
        data: order_string,
        cache: false,
        success: function(data){    
            $("#response").html(data);
            $("#response").slideDown('slow');
            slideout();
        }
    });               
    }         
    });
   });
  
}); 
</script>
</head>
<body>
<center>  
<p><h1>Dynamic Drag and Drop Order List With jQuery Ajax and Python Flask PostgreSQL Database</h1></p>
<div style="width:300px;">
  <div id="list">
  <div id="response"> </div>
      <ul class="reorder">
        {% for row in dragdrop %}
        <li id="{{row.id}}">{{row.text}}
          <div class="clear"></div>
        </li>
        {% endfor %}
      </ul>
  </div>
</div>
</center>

<style>
ul {
 padding:0px;
 margin: 0px;
}
#response {
 padding:10px;
 background-color:#9F9;
 border:2px solid #396;
 margin-bottom:20px;
}
#list li {
 margin: 0 0 3px;
 padding:8px;text-align:left;
 background-color:#00CCCC;
 color:#fff;
 list-style: none;
 border: #CCCCCC solid 1px;
}
</style>
</body>
</html>

Saturday, July 3, 2021

Date Range Search with Python Flask PostgreSQL jQuery Ajax and DatePicker

Date Range Search with Python Flask PostgreSQL jQuery Ajax and DatePicker

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

Datepicker https://jqueryui.com/datepicker/

CREATE TABLE orders (
id serial PRIMARY KEY,
customer_name VARCHAR ( 150 ) NOT NULL,
purchased_items VARCHAR ( 150 ) NOT NUL,L
purchased_date TIMESTAMP NOT NULL,
price DOUBLE PRECISION
);


INSERT INTO
    orders(customer_name,purchased_items,purchased_date,price)
VALUES
('Airi Satou', 'iPhone', '2020-05-07', 649.00),
('Angelica Ramos', 'Samsung Galaxy', '2020-11-10', 2500.00),
('Ashton Cox', 'Infinix Note 7', '2020-09-10', 299.09),
('Bradley Greer', 'Macbook Pro', '2020-11-26', 1799.50),
('Brenden Wagner', 'Samsung 50\" Smart 4K UHD TV ', '2020-11-27', 479.00),
('Brielle Williamson', '7 Series Curved LED 4K UHD', '2019-11-27', 269.00),
('Bruno Nash', 'iMac', '2019-11-28', 1999.05),
('Caesar Vance', 'Dell Inspiron 3573', '2019-11-30', 1999.05),
('Cara Stevens', 'Tlc 40inch tv Roku tv', '2019-12-07', 649.00),
('Cedric Kelly', 'Acer Aspire 3', '2021-01-13', 199.00);
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify, flash, redirect
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 orders ORDER BY id desc")
    orders = cur.fetchall() 
    return render_template('index.html', orders=orders)
  
@app.route("/range",methods=["POST","GET"])
def range(): 
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor) 
    if request.method == 'POST':
        From = request.form['From']
        to = request.form['to']
        print(From)
        print(to)
        query = "SELECT * from orders WHERE purchased_date BETWEEN '{}' AND '{}'".format(From,to)
        cur.execute(query)
        ordersrange = cur.fetchall()
    return jsonify({'htmlresponse': render_template('response.html', ordersrange=ordersrange)})

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Date Range Search with Python Flask PostgreSQL jQuery Ajax and DatePicker</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css"/>
</head>
<body>
<br/>
<div class="container">
    <h2 align="center">Date Range Search with Python Flask PostgreSQL jQuery Ajax and DatePicker</h2>
    <br/>
    <div class="row">
    <div class="col-md-2">
        <input type="text" name="From" id="From" class="form-control" placeholder="From Date"/>
    </div>
    <div class="col-md-2">
        <input type="text" name="to" id="to" class="form-control" placeholder="To Date"/>
    </div>
    <div class="col-md-8">
        <input type="button" name="range" id="range" value="Range" class="btn btn-success"/>
    </div>
    <div class="clearfix"></div>
    <br/>
    </div>
    <div id="purchase_order">
    <table class="table table-bordered">
        <tr>
        <th width="5%">ID</th>
        <th width="35%">Customer Name</th>
        <th width="40%">Purchased Item</th>
        <th width="20%">Purchased Date</th>
        <th width="20%">Price</th>
        </tr>
        {% for row in orders %}
        <tr>
            <td>{{row.id}}</td>
            <td>{{row.customer_name}}</td>
            <td>{{row.purchased_items}}</td>
            <td>{{row.purchased_date}}</td>
            <td>$ {{row.price}}</td>
        </tr>
        {% endfor %}
    </table>
    </div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function(){
    $.datepicker.setDefaults({
        dateFormat: 'yy-mm-dd'
    });
    $(function(){
        $("#From").datepicker();
        $("#to").datepicker();
    });
    $('#range').click(function(){
        var From = $('#From').val();
        var to = $('#to').val();
        if(From != '' && to != '')
        {
            $.ajax({
                url:"/range",
                method:"POST",
                data:{From:From, to:to},
                success:function(data)
                {
                    $('#purchase_order').html(data);
                    $('#purchase_order').append(data.htmlresponse);
                }
            });
        }
        else
        {
            alert("Please Select the Date");
        }
    });
});
</script>
</body>
</html>
templates/response.html
//templates/response.html
<table class="table table-bordered">
    <tr>
    <th width="5%">ID</th>
    <th width="35%">Customer Name</th>
    <th width="40%">Purchased Item</th>
    <th width="20%">Purchased Date</th>
    <th width="20%">Price</th>
    </tr>
    {% for row in ordersrange %}
        <tr>
        <td>{{row.id}}</td>
        <td>{{row.customer_name}}</td>
        <td>{{row.purchased_items}}</td>
        <td>{{row.purchased_date}}</td>
        <td>{{row.price}}</td>
        </tr>
    {% endfor %}
</table>

Friday, July 2, 2021

Login Form Using Bootstrap Modal using Python Flask jquery Ajax password hash and session

Login Form Using Bootstrap Modal using Python Flask jquery Ajax password hash and session

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 admin_login (
id serial PRIMARY KEY,
admin_name VARCHAR ( 150 ) NOT NULL,
admin_password VARCHAR ( 150 ) NOT NULL
);

INSERT INTO
    admin_login(admin_name,admin_password)
VALUES
('admin', 'pbkdf2:sha256:150000$FXLDgm3a$bd46f6b7b44124a523f9566d03bf110ba2ebf28bfd3522faeddd56eabebcb7f5');
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify, flash, redirect, session
from werkzeug.security import generate_password_hash, check_password_hash
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():
    hash = generate_password_hash('cairocoders')
    check_hash = check_password_hash(hash, 'cairocoders')   
    return render_template('index.html', hash=hash, check_hash=check_hash)
 
@app.route("/action",methods=["POST","GET"])
def action(): 
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        print(username)
        print(password)
        cur.execute("SELECT * FROM admin_login WHERE admin_name = %s", [username,])
        total_row = cur.rowcount
        print(total_row)

        if total_row > 0:
            data = cur.fetchone()
            rs_password = data['admin_password']
            print(rs_password)
            if check_password_hash(rs_password, password):
                session['logged_in'] = True
                session['username'] = username
                msg = 'success'
            else:
               msg = 'No-data'
        else:
            msg = 'No-data'   
    return jsonify(msg)   
 
@app.route('/logout')
def logout():
    session.clear()
    return redirect('/')

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>  
 <html>  
<head>  
<title>Login Form Using Bootstrap Modal using Python Flask jquery Ajax password hash and session</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>
</head>  
<body>  
<div class="container" style="width:700px;">  
                <h3 align="center">Login Form Using Bootstrap Modal using Python Flask jquery Ajax password hash and session</h3><br />  
                <br />  
                <br />  
                <!--<p>hash : {{ hash }}</p>
                <p>hash : {{ check_hash }}</p> -->
                <br />  
                <br />  
                <br />  
                {% if session.logged_in %}
                <div align="center">  
                     <h1>Welcome - {{session.username}}</h1><br />  
                     <a href="/logout">Logout</a>  
                </div>  
                {% else %}  
                <div align="center">  
                     <a data-target="#myModal" role="button" class="btn btn-warning" data-toggle="modal"><span class="glyphicon glyphicon-hand-up"></span>Login</a>
                </div>  
                {% endif %} 
           </div>  
           <br />  
             
 <div id="myModal" class="modal fade">  
      <div class="modal-dialog">  
   <!-- Modal content-->  
           <div class="modal-content">  
                <div class="modal-header">  
                     <button type="button" class="close" data-dismiss="modal">×</button>  
                     <h4 class="modal-title">Login Form Using Bootstrap Modal using Python Flask jquery Ajax password hash and session</h4>  
                </div>  
                <div class="modal-body">  
                     <label>Username</label>  
                     <input type="text" name="username" id="username" class="form-control" />  
                     <br />  
                     <label>Password</label>  
                     <input type="password" name="password" id="password" class="form-control" />  
                     <br />  
                     <button type="button" name="login_button" id="login_button" class="btn btn-warning">Login</button>  
                </div>  
           </div>  
      </div>  
 </div>  
 <script>  
 $(document).ready(function(){  
      $('#login_button').click(function(){  
           var username = $('#username').val();  
           var password = $('#password').val();  
           if(username != '' && password != '')  
           {  
                $.ajax({  
                     url:"/action",  
                     method:"POST",  
                     data: {username:username, password:password},  
                     success:function(data)  
                     {  
                          alert(data);  
                          if(data == 'No-data')  
                          {  
                               alert("Invalid Email Or Password!");  
                          }  
                          else 
                          {  
                               $('#loginModal').hide();  
                               location.reload();  
                          }  
                     }  
                });  
           }  
           else 
           {  
                alert("Both Fields are required");  
           }  
      });    
 });  
</script>   
</body>  
 </html>  
 

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>

ExpressJS Simple Form POST

ExpressJS Simple Form POST

run
PS C:\nodeproject> node index.js

http://localhost:3000/
index.js
//index.js
const express = require('express')
const app = express()
const port = 3000
var bodyParser = require('body-parser');

// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

app.use(express.static('public'));
app.get('/index.html', function (req, res) {
   res.sendFile( __dirname + "/" + "index.html" );
})

app.post('/process_post', urlencodedParser, function (req, res) {
  // Prepare output in JSON format
  response = {
    username:req.body.username,
    password:req.body.password
  };
  console.log(response);
  res.end(JSON.stringify(response));
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})
public/index.html
//public/index.html
<!DOCTYPE html>
<html>
<head>
 <meta charset="UTF-8">
 <title>ExpressJS Simple Form POST</title>
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
   <body>
      <div id="login">
         <h3 class="text-center pt-5">ExpressJS Simple Form POST</h3>
         <div class="container">
             <div id="login-row" class="row justify-content-center align-items-center">
                 <div id="login-column" class="col-md-6">
                     <div id="login-box" class="col-md-12">
                         <form action="http://localhost:3000/process_post" method="POST" id="login-form" class="form">
                             <h3 class="text-center text-info">Login</h3>
                             <div class="form-group">
                                 <label for="username" class="text-info">Username:</label><br>
                                 <input type="text" name="username" id="username" class="form-control" autocomplete="off">
                             </div>
                             <div class="form-group">
                                 <label for="password" class="text-info">Password:</label><br>
                                 <input type="password" name="password" id="password" class="form-control">
                             </div>
                             <div class="form-group">
                                 <label for="remember-me" class="text-info"><span>Remember me</span> <span><input id="remember-me" name="remember-me" type="checkbox"></span></label><br>
                                 <input type="submit" name="submit" class="btn btn-info btn-md" value="submit">
                             </div>
                             <div id="register-link" class="text-right">
                                 <a href="#" class="text-info">Register here</a>
                             </div>
                         </form>
                     </div>
                 </div>
             </div>
         </div>
     </div>
<style>
#login .container #login-row #login-column #login-box {
  margin-top: 120px;
  max-width: 600px;
  height: 320px;
  border: 1px solid #9C9C9C;
  background-color: #EAEAEA;
}
#login .container #login-row #login-column #login-box #login-form {
  padding: 20px;
}
#login .container #login-row #login-column #login-box #login-form #register-link {
  margin-top: -85px;
}
</style>   
   </body>
</html>

ExpressJS Simple Form GET

ExpressJS Simple Form GET index.js

run
PS C:\nodeproject> node index.js

http://localhost:3000/
//index.js
const express = require('express')
const app = express()
const port = 3000

app.use(express.static('public'));
app.get('/index.htm', function (req, res) {
   res.sendFile( __dirname + "/" + "index.html" );
})

app.get('/process_get', function (req, res) {
  // Prepare output in JSON format
  response = {
    username:req.query.username,
    password:req.query.password
  };
  console.log(response);
  res.end(JSON.stringify(response));
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})
public/index.html
//public/index.html
<!DOCTYPE html>
<html>
<head>
 <meta charset="UTF-8">
 <title>ExpressJS Simple Form GET</title>
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
   <body>
      <div id="login">
         <h3 class="text-center pt-5">ExpressJS Simple Form GET</h3>
         <div class="container">
             <div id="login-row" class="row justify-content-center align-items-center">
                 <div id="login-column" class="col-md-6">
                     <div id="login-box" class="col-md-12">
                         <form action="http://localhost:3000/process_get" method = "GET" id="login-form" class="form">
                             <h3 class="text-center text-info">Login</h3>
                             <div class="form-group">
                                 <label for="username" class="text-info">Username:</label><br>
                                 <input type="text" name="username" id="username" class="form-control" autocomplete="off">
                             </div>
                             <div class="form-group">
                                 <label for="password" class="text-info">Password:</label><br>
                                 <input type="password" name="password" id="password" class="form-control">
                             </div>
                             <div class="form-group">
                                 <label for="remember-me" class="text-info"><span>Remember me</span> <span><input id="remember-me" name="remember-me" type="checkbox"></span></label><br>
                                 <input type="submit" name="submit" class="btn btn-info btn-md" value="submit">
                             </div>
                             <div id="register-link" class="text-right">
                                 <a href="#" class="text-info">Register here</a>
                             </div>
                         </form>
                     </div>
                 </div>
             </div>
         </div>
     </div>
<style>
#login .container #login-row #login-column #login-box {
  margin-top: 120px;
  max-width: 600px;
  height: 320px;
  border: 1px solid #9C9C9C;
  background-color: #EAEAEA;
}
#login .container #login-row #login-column #login-box #login-form {
  padding: 20px;
}
#login .container #login-row #login-column #login-box #login-form #register-link {
  margin-top: -85px;
}
</style>   
   </body>
</html>

Thursday, July 1, 2021

Fullcalandar CRUD(Create, Read, Update, Delete) with Python Flask Jquery Ajax and PostgreSQL

Fullcalandar CRUD(Create, Read, Update, Delete) with Python Flask Jquery Ajax and PostgreSQL

This tutorial is a Jquery Fullcalandar Integration FullCalendar.js plugin https://fullcalendar.io/demos

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 events (
id serial PRIMARY KEY,
title VARCHAR ( 150 ) NOT NULL,
start_event TIMESTAMP NOT NULL,
end_event TIMESTAMP NOT NULL
);

INSERT INTO
    events(title,start_event,end_event)
VALUES
('Python Flask coding visual studio', '2021-07-03 16:00:00', '2021-07-04 03:00:00'),
('PHP coding Notepad++', '2021-07-08 03:17:15', '2021-07-10 04:00:00'),
('Basketball', '2021-07-05 00:00:00', '2021-07-05 14:30:00'),
('Birthday Party', '2021-07-12 00:00:00', '2021-07-13 00:00:00');
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 events ORDER BY id")
    calendar = cur.fetchall()  
    return render_template('index.html', calendar = calendar)
 
@app.route("/insert",methods=["POST","GET"])
def insert():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        title = request.form['title']
        start = request.form['start']
        end = request.form['end']
        print(title)     
        print(start)  
        cur.execute("INSERT INTO events (title,start_event,end_event) VALUES (%s,%s,%s)",[title,start,end])
        conn.commit()       
        cur.close()
        msg = 'success'  
    return jsonify(msg)
 
@app.route("/update",methods=["POST","GET"])
def update():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        title = request.form['title']
        start = request.form['start']
        end = request.form['end']
        id = request.form['id']
        print(title)     
        print(start)  
        cur.execute("UPDATE events SET title = %s, start_event = %s, end_event = %s WHERE id = %s ", [title, start, end, id])
        conn.commit()       
        cur.close()
        msg = 'success'  
    return jsonify(msg)    
 
@app.route("/ajax_delete",methods=["POST","GET"])
def ajax_delete():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        getid = request.form['id']
        print(getid)
        cur.execute('DELETE FROM events WHERE id = {0}'.format(getid))
        conn.commit()       
        cur.close()
        msg = 'Record deleted successfully'  
    return jsonify(msg) 
 
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
 <head>
  <title>Fullcalandar CRUD(Create, Read, Update, Delete) with Python Flask Jquery Ajax and PostgreSQL</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.css" />
  <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>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.js"></script>
  <script>
  $(document).ready(function() {
   var calendar = $('#calendar').fullCalendar({
    editable:true,
    header:{
     left:'prev,next today',
     center:'title',
     right:'month,agendaWeek,agendaDay'
    },
    events: [{% for row in calendar %}{ id : '{{row.id}}', title : '{{row.title}}', start : '{{row.start_event}}', end : '{{row.end_event}}', }, {% endfor %}],
    selectable:true,
    selectHelper:true,
    select: function(start, end, allDay)
    {
     var title = prompt("Enter Event Title");
     if(title)
     {
      var start = $.fullCalendar.formatDate(start, "Y-MM-DD HH:mm:ss");
      var end = $.fullCalendar.formatDate(end, "Y-MM-DD HH:mm:ss");
      $.ajax({
       url:"/insert",
       type:"POST",
       data:{title:title, start:start, end:end},
       success:function(data)
       {
         //alert(data)
        alert("Added Successfully");
        window.location.replace("/");
       }
      })
     }
    },
    editable:true,
    eventResize:function(event)
    {
     var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm:ss");
     var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD HH:mm:ss");
     var title = event.title;
     var id = event.id;
     $.ajax({
      url:"/update",
      type:"POST",
      data:{title:title, start:start, end:end, id:id},
      success:function(){
       calendar.fullCalendar('refetchEvents');
       alert('Event Update');
      }
     })
    },
     
    eventDrop:function(event)
    {
     var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm:ss");
     var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD HH:mm:ss");
     var title = event.title;
     var id = event.id;
     $.ajax({
      url:"/update",
      type:"POST",
      data:{title:title, start:start, end:end, id:id},
      success:function()
      {
       calendar.fullCalendar('refetchEvents');
       alert("Event Updated");
      }
     });
    },
 
    eventClick:function(event)
    {
     if(confirm("Are you sure you want to remove it?"))
     {
      var id = event.id;
      $.ajax({
       url:"/ajax_delete",
       type:"POST",
       data:{id:id},
       success:function()
       {
        calendar.fullCalendar('refetchEvents');
        alert("Event Removed");
       }
      })
     }
    },
 
   });
  });
    
  </script>
 </head>
 <body>
  <br />
  <h2 align="center"><a href="#">Fullcalandar CRUD(Create, Read, Update, Delete) with Python Flask Jquery Ajax and PostgreSQL</a></h2>
  <br />
  <div class="container">
   <div id="calendar"></div>
  </div>
 </body>
</html>

Related Post