article

Wednesday, May 5, 2021

SwiftUI How to show alert

SwiftUI How to show alert

Basic SwiftUI alerts look like this:

Alert(title: Text("This is a message"), message: Text("succcess message"), dismissButton: .default(Text("Got it!")))
 
//
//  ContentView.swift
//  Testapp
//
//  Created by Cairocoders 
//

import SwiftUI

struct ContentView: View {
    
    @State private var showAlert = false
    
    var body: some View {
        
        Button("Show Alert") {
            showAlert = true
        }
        .alert(isPresented: $showAlert) {
            Alert(title: Text("Important message"), message: Text("this is a success messge"), dismissButton: .default(Text("Got It!")))
        }
    }
}

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

import SwiftUI

struct Swifuiprogram: Identifiable {
    var id: String { name }
    let name: String
}
struct ContentView: View {
    
    @State private var selecprogramming: Swifuiprogram?
    var body: some View {
        VStack(spacing: 20) {
            Text("What is your programming language")
                .font(.headline)
            
            Button("Select SwiftUI") {
                selecprogramming = Swifuiprogram(name: "SwiftUI")
            }
            
            Button("Select IOS") {
                selecprogramming = Swifuiprogram(name: "IOS")            }
        }
        .alert(item: $selecprogramming) { show in
            Alert(title: Text(show.name), message: Text("Great choice"), dismissButton: .cancel())
        }

    }
}

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

Tuesday, May 4, 2021

Jquery AJAX Check Availability username with Python Flask PostgreSQL

Jquery AJAX Check Availability username with Python Flask 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
CREATE TABLE users (
id serial PRIMARY KEY,
fullname VARCHAR ( 100 ) NOT NULL,
username VARCHAR ( 50 ) NOT NULL,
password VARCHAR ( 255 ) NOT NULL,
email VARCHAR ( 50 ) NOT NULL
);

PostgreSQL SERIAL To Create Auto-increment Column
CREATE TABLE users (
id serial PRIMARY KEY
);
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify
import psycopg2 #pip install psycopg2 
import psycopg2.extras

app = Flask(__name__)

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('home.html')

@app.route('/user_check', methods=['POST'])
def username_check():
    username = request.form['username']
    print(username)  
    # validate the received values
    if username and request.method == 'POST':  

        cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

        cursor.execute('SELECT * FROM users WHERE username = %s', (username,))
        row = cursor.fetchone()
                
        if row:
            resp = jsonify('Username unavailable')
            resp.status_code = 200
            return resp
        else:
            resp = jsonify('Username available')
            resp.status_code = 200
            return resp
    else:
        resp = jsonify('Username is required field.')
        resp.status_code = 200
        return resp

if __name__ == "__main__":
    app.run(debug=True)
templates/home.html
//templates/home.html
<!DOCTYPE html>
<html>
<head>
 <meta charset="UTF-8">
 <title>Jquery AJAX Check Availability username with Python Flask PostgreSQL</title>
 <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
 <div style="margin: 10px 0 0 10px;width: 600px">
  <h3>Jquery AJAX Check Availability username with Python Flask PostgreSQL</h3>
   
  <form id="signupform" style="padding: 10px;">
   <fieldset>
    <legend>Check username</legend>
    <div>
     <p style="padding-bottom:5px;font-weight:bold;">Username</p>
     <input type="text" class="form-control" name="username" id="username" autocomplete="off"/>
     <div id="msg"></div>
     <h4 id='loading' style="display:none;"><img src="{{ url_for('static', filename='img/loader.gif') }}"/> Loading..</h4>
    </div>
   </fieldset>
  </form>
 </div>
 <script type="text/javascript">
  $(document).ready(function() {
   $("#username").on('input', function(e) {
    $('#msg').hide();
    $('#loading').show();
    if ($('#username').val() == null || $('#username').val() == "") {
     $('#msg').show();
     $("#msg").html("Username is required field.").css("color", "red");
    } else {
     $.ajax({
      type: "POST",
      url: "/user_check",
      data: $('#signupform').serialize(),
      dataType: "html",
      cache: false,
      success: function(msg) {
       $('#msg').show();
       $('#loading').hide();
       $("#msg").html(msg);
      },
      error: function(jqXHR, textStatus, errorThrown) {
       $('#msg').show();
       $('#loading').hide();
       $("#msg").html(textStatus + " " + errorThrown);
      }
     });
    }
   });
  });
 </script>
<style>
body {font-size:16px;}
#msg {font-weight:bold;padding:10px;}
.error { color: red;}
.form-control {
    display: block;
    width:300px;
    height: 25px;
    padding: 6px 12px;
    font-size: 14px;
    line-height: 1.428571429;
    color: #555;
    background-color: #fff;
    background-image: none;
    border: 1px solid #ccc;
    border-radius: 4px;
    -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
    box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
    -webkit-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
    transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
}
</style> 
</body>
</html>

SwiftUI implement WebView(WebKit)

SwiftUI implement WebView(WebKit)
//
//  ViewController.swift
//  web
//
//  Created by Cairocoders
//

import UIKit
import WebKit

class ViewController: UIViewController {

    let webView = WKWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(webView)
        
        guard let url = URL(string: "https://tutorial101.blogspot.com") else {
            return
        }
        webView.load(URLRequest(url: url))
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        webView.frame = view.bounds
    }


}

Todo app SwiftUI iOS and UserDefaults database

Todo app SwiftUI iOS and UserDefaults database
 
//
//  ContentView.swift
//  todos
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View { //User Interface
    
    @State private var newTodo = ""
    @State private var allTodos: [TodoItem] = []
    private let todosKey = "todosKey"
    
    var body: some View {
      NavigationView {
        VStack { //vertical stack
            
            HStack { //Horizontal Stack
            TextField("Add todo...", text: $newTodo)
              .textFieldStyle(RoundedBorderTextFieldStyle())
            
            Button(action: {
              guard !self.newTodo.isEmpty else { return }
              self.allTodos.append(TodoItem(todo: self.newTodo))
              self.newTodo = ""
              self.saveTodos()
            }) {
                Image(systemName: "plus")
            }
            .padding(.leading, 5)
          }.padding() //end horizontal stack

          List { //List view to display all of the to-dos in our allTodos
            ForEach(allTodos) { todoItem in
              Text(todoItem.todo)
            }.onDelete(perform: deleteTodo)
          }
            
        }//end vertical stack
        .navigationBarTitle("Todos")
      }.onAppear(perform: loadTodos)
    }
    
    //Storing To-dos in UserDefaults
    //UserDefaults is a database where you store key-value
    //https://developer.apple.com/documentation/foundation/userdefaults
    
    private func saveTodos() {
      UserDefaults.standard.set(try? PropertyListEncoder().encode(self.allTodos), forKey: todosKey)
    }
    
    private func loadTodos() {
      if let todosData = UserDefaults.standard.value(forKey: todosKey) as? Data {
        if let todosList = try? PropertyListDecoder().decode(Array<TodoItem>.self, from: todosData) {
          self.allTodos = todosList
        }
      }
    }
    
    private func deleteTodo(at offsets: IndexSet) {
      self.allTodos.remove(atOffsets: offsets)
      saveTodos()
    }
    
}

//Add codable to make Sure each item encoded and decoded
struct TodoItem: Codable, Identifiable { //Identifiable protocol this ensures that the system can distinguish one TodoItem from another
    var id = UUID()
  let todo: String
}

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

Saturday, May 1, 2021

Python Flask jQuery Ajax POST and insert data to PostgreSQL

Python Flask jQuery Ajax POST and insert data to 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
CREATE TABLE users (
id serial PRIMARY KEY,
fullname VARCHAR ( 100 ) NOT NULL,
username VARCHAR ( 50 ) NOT NULL,
password VARCHAR ( 255 ) NOT NULL,
email VARCHAR ( 50 ) NOT NULL
);

PostgreSQL SERIAL To Create Auto-increment Column
CREATE TABLE users (
id serial PRIMARY KEY
);
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify
import psycopg2 #pip install psycopg2 
import psycopg2.extras
from werkzeug.security import generate_password_hash, check_password_hash

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 index():
    return render_template('home.html')
 
@app.route('/process', methods=['POST'])
def process():
    cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

    msg = ''
    fullname = request.form['fullname']
    username = request.form['username']
    txtmail = request.form['txtmail']
    password = request.form['password']
    _hashed_password = generate_password_hash(password)
    print(fullname)
    if fullname and txtmail and username and password:
        cursor.execute("INSERT INTO users (fullname, username, password, email) VALUES (%s,%s,%s,%s)", (fullname, username, _hashed_password, txtmail))
        conn.commit()
        print('success')
        msg = 'You have successfully registered!'
        return jsonify({'name' : msg})

if __name__ == "__main__":
    app.run(debug=True)
templates/home.html
//templates/home.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>Python Flask jQuery Ajax POST and insert data to PostgreSQL </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>
   <script>
   $(document).ready(function() {
       $('form').on('submit', function(event) {
           $('#loading').show();
           $.ajax({
               data : {
                   fullname : $('#fullname').val(),
                   username : $('#username').val(),
                   password : $('#password').val(),
                   txtmail : $('#txtmail').val()
               },
               type : 'POST',
               url : '/process'
           })
           .done(function(data) {
               if (data.error) {
                   $('#errorAlert').text(data.error).show();
                   $('#successAlert').hide();
                   $('#loading').hide();
               }
               else {
                   $('#successAlert').text(data.name).show();
                   $('#errorAlert').hide();
                   $('#loading').hide();
               }
    
           });
           event.preventDefault();
       });
   });
   </script>
   </head>
    <body>
         <div class="container">
           <p><h1>Python Flask jQuery Ajax POST and insert data to PostgreSQL</h1></p>
           <div class="col-md-4 col-md-offset-4" id="login">
               <section id="inner-wrapper" class="login">
                               <article>
                                   <form class="form-signin">
                                   <h2 class="form-signin-heading">Please Sign Up </h2>
                                       <div class="form-group">
                                           <div class="input-group">
                                               <span class="input-group-addon"><i class="fa fa-user"> </i></span>
                                               <input type="text" class="form-control" name="fullname" id="fullname" placeholder="Your Name" required autofocus>
                                           </div>
                                       </div>
                                       <div class="form-group">
                                           <div class="input-group">
                                               <span class="input-group-addon"><i class="fa fa-user"> </i></span>
                                               <input type="text" class="form-control" name="username" id="username" placeholder="Your Username" required>
                                           </div>
                                       </div>
                                       <div class="form-group">
                                           <div class="input-group">
                                               <span class="input-group-addon"><i class="fa fa-envelope"> </i></span>
                                               <input type="email" class="form-control" name="txtmail" id="txtmail" placeholder="Email Address" required>
                                           </div>
                                       </div>
                                       <div class="form-group">
                                           <div class="input-group">
                                               <span class="input-group-addon"><i class="fa fa-key"> </i></span>
                                               <input type="password" class="form-control" name="password" id="password" class="form-control" placeholder="Password" required>
                                           </div>
                                       </div>
                                         <button type="submit" class="btn btn-success btn-block">Register</button>
                                   </form>
                                   <br/>
                   <div id="successAlert" class="alert alert-success" role="alert" style="display:none;"></div>
                   <div id="errorAlert" class="alert alert-danger" role="alert" style="display:none;"></div>
                   <h4 id='loading' style="display:none;"><img src="{{ url_for('static', filename='img/loader.gif') }}"/> Loading..</h4>
                    
                    
                               </article>
               </section>            
           </div>                
   </div>        
   <style>
   body {
       background:#333;
   }
   h1 {color:#fff;}
   #login {
       -webkit-perspective: 1000px;
       -moz-perspective: 1000px;
       perspective: 1000px;
       margin-top:50px;
       margin-left:30%;
   }
   .login {
       font-family: 'Josefin Sans', sans-serif;
       -webkit-transition: .3s;
       -moz-transition: .3s;
       transition: .3s;
       -webkit-transform: rotateY(40deg);
       -moz-transform: rotateY(40deg);
       transform: rotateY(40deg);
   }
   .login:hover {
       -webkit-transform: rotate(0);
       -moz-transform: rotate(0);
       transform: rotate(0);
   }
   .login .form-group {
       margin-bottom:17px;
   }
   .login .form-control,
   .login .btn {
       border-radius:0;
   }
   .login .btn {
       text-transform:uppercase;
       letter-spacing:3px;
   }
   .input-group-addon {
       border-radius:0;
       color:#fff;
       background:#f3aa0c;
       border:#f3aa0c;
   }
   .forgot {
       font-size:16px;
   }
   .forgot a {
       color:#333;
   }
   .forgot a:hover {
       color:#5cb85c;
   }
    
   #inner-wrapper, #contact-us .contact-form, #contact-us .our-address {
       color: #1d1d1d;
       font-size: 19px;
       line-height: 1.7em;
       font-weight: 300;
       padding: 50px;
       background: #fff;
       box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12);
       margin-bottom: 100px;
   }
   .input-group-addon {
       border-radius: 0;
           border-top-right-radius: 0px;
           border-bottom-right-radius: 0px;
       color: #fff;
       background: #f3aa0c;
       border: #f3aa0c;
           border-right-color: rgb(243, 170, 12);
           border-right-style: none;
           border-right-width: medium;
   }
   </style>              
    </body>
    </html>

Wednesday, April 28, 2021

Python Flask postgreSQL Login Register Sytem with password hash

Python Flask postgreSQL Login Register Sytem with password hash

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
CREATE TABLE users (
id serial PRIMARY KEY,
fullname VARCHAR ( 100 ) NOT NULL,
username VARCHAR ( 50 ) NOT NULL,
password VARCHAR ( 255 ) NOT NULL,
email VARCHAR ( 50 ) NOT NULL
);

PostgreSQL SERIAL To Create Auto-increment Column
CREATE TABLE users (
id serial PRIMARY KEY
);
SMALLSERIAL = 2 bytes = 1 to 32,767
SERIAL = 4 bytes = 1 to 2,147,483,647
BIGSERIAL = 8 bytes = 1 to 9,223,372,036,854,775,807

app.py
#app.py
from flask import Flask, request, session, redirect, url_for, render_template, flash
import psycopg2 #pip install psycopg2 
import psycopg2.extras
import re 
from werkzeug.security import generate_password_hash, check_password_hash

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():
    # Check if user is loggedin
    if 'loggedin' in session:
   
        # User is loggedin show them the home page
        return render_template('home.html', username=session['username'])
    # User is not loggedin redirect to login page
    return redirect(url_for('login'))

@app.route('/login/', methods=['GET', 'POST'])
def login():
    cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
  
    # Check if "username" and "password" POST requests exist (user submitted form)
    if request.method == 'POST' and 'username' in request.form and 'password' in request.form:
        username = request.form['username']
        password = request.form['password']
        print(password)

        # Check if account exists using MySQL
        cursor.execute('SELECT * FROM users WHERE username = %s', (username,))
        # Fetch one record and return result
        account = cursor.fetchone()

        if account:
            password_rs = account['password']
            print(password_rs)
            # If account exists in users table in out database
            if check_password_hash(password_rs, password):
                # Create session data, we can access this data in other routes
                session['loggedin'] = True
                session['id'] = account['id']
                session['username'] = account['username']
                # Redirect to home page
                return redirect(url_for('home'))
            else:
                # Account doesnt exist or username/password incorrect
                flash('Incorrect username/password')
        else:
            # Account doesnt exist or username/password incorrect
            flash('Incorrect username/password')

    return render_template('login.html')
 
@app.route('/register', methods=['GET', 'POST'])
def register():
    cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

    # Check if "username", "password" and "email" POST requests exist (user submitted form)
    if request.method == 'POST' and 'username' in request.form and 'password' in request.form and 'email' in request.form:
        # Create variables for easy access
        fullname = request.form['fullname']
        username = request.form['username']
        password = request.form['password']
        email = request.form['email']
   
        _hashed_password = generate_password_hash(password)

        #Check if account exists using MySQL
        cursor.execute('SELECT * FROM users WHERE username = %s', (username,))
        account = cursor.fetchone()
        print(account)
        # If account exists show error and validation checks
        if account:
            flash('Account already exists!')
        elif not re.match(r'[^@]+@[^@]+\.[^@]+', email):
            flash('Invalid email address!')
        elif not re.match(r'[A-Za-z0-9]+', username):
            flash('Username must contain only characters and numbers!')
        elif not username or not password or not email:
            flash('Please fill out the form!')
        else:
            # Account doesnt exists and the form data is valid, now insert new account into users table
            cursor.execute("INSERT INTO users (fullname, username, password, email) VALUES (%s,%s,%s,%s)", (fullname, username, _hashed_password, email))
            conn.commit()
            flash('You have successfully registered!')
    elif request.method == 'POST':
        # Form is empty... (no POST data)
        flash('Please fill out the form!')
    # Show registration form with message (if any)
    return render_template('register.html')
  
  
@app.route('/logout')
def logout():
    # Remove session data, this will log the user out
   session.pop('loggedin', None)
   session.pop('id', None)
   session.pop('username', None)
   # Redirect to login page
   return redirect(url_for('login'))
 
@app.route('/profile')
def profile(): 
    cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
  
    # Check if user is loggedin
    if 'loggedin' in session:
        cursor.execute('SELECT * FROM users WHERE id = %s', [session['id']])
        account = cursor.fetchone()
        # Show the profile page with account info
        return render_template('profile.html', account=account)
    # User is not loggedin redirect to login page
    return redirect(url_for('login'))

if __name__ == "__main__":
    app.run(debug=True)
templates/login.html
//templates/login.html
<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>Login</title>
  <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css">
 <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 style="background-color:#ccc;">
  <div class="login-box" >
  <div class="login-header">Login</div>
  <div class="login-body">
    <p>Please enter your username and password</p>
    <form class="form-group" action="{{ url_for('login') }}" method="post">
        <label>Username</label>
        <input type="text" class="form-control" name="username" placeholder="Username" id="username" required>
        <label>Password</label>
        <input type="password" class="form-control" name="password" placeholder="Password" id="password" required>
        <input type="checkbox" value="checked"><b>Remember</b>
        <input type="submit" value="Login" class="form-control btn btn-success " name="">
    </form>
    {% with messages = get_flashed_messages()  %}
    {% if messages %}
    {% for message in messages %}
    <div class="alert alert-success alert-dismissible fade show" role="alert">
      {{ message }}
      <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">×</span>
      </button>
    </div>
    {% endfor %}
    {% endif %}
    {% endwith %}
    <p>No account <a href="{{ url_for('register') }}">Register</a></p>
  </div>
 </div>
 </body>
</html>
templates/register.html
//templates/register.html
<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>Register</title>
  <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css">
  <!-- Google Fonts -->
  <link href='https://fonts.googleapis.com/css?family=Passion+One' rel='stylesheet' type='text/css'>
  <link href='https://fonts.googleapis.com/css?family=Oxygen' rel='stylesheet' type='text/css'>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
 </head>
 <body style="background-color:#ccc;">
 <div class="container">
   <div class="row main">
    <div class="main-login main-center">
    <h5>Register New user or login existing account</h5>
     <form action="{{ url_for('register') }}" method="post" autocomplete="off"> 
      <div class="form-group">
       <label for="name" class="cols-sm-2 control-label">Your Name</label>
       <div class="cols-sm-10">
        <div class="input-group">
         <span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"></i></span>
         <input type="text" class="form-control" name="fullname" id="fullname"  placeholder="Enter your Name"/>
        </div>
       </div>
      </div>
      <div class="form-group">
       <label for="email" class="cols-sm-2 control-label">Your Email</label>
       <div class="cols-sm-10">
        <div class="input-group">
         <span class="input-group-addon"><i class="fa fa-envelope fa" aria-hidden="true"></i></span>
         <input type="text" class="form-control" name="email" id="email"  placeholder="Enter your Email"/>
        </div>
       </div>
      </div>
 
      <div class="form-group">
       <label for="username" class="cols-sm-2 control-label">Username</label>
       <div class="cols-sm-10">
        <div class="input-group">
         <span class="input-group-addon"><i class="fa fa-users fa" aria-hidden="true"></i></span>
         <input type="text" class="form-control" name="username" id="username" placeholder="Enter your Username" required>
        </div>
       </div>
      </div>
 
      <div class="form-group">
       <label for="password" class="cols-sm-2 control-label">Password</label>
       <div class="cols-sm-10">
        <div class="input-group">
         <span class="input-group-addon"><i class="fa fa-lock fa-lg" aria-hidden="true"></i></span>
         <input type="password" class="form-control" name="password" placeholder="Password" id="password" required  placeholder="Enter your Password"/>
        </div>
       </div>
      </div>
 
      <div class="form-group ">
        {% with messages = get_flashed_messages()  %}
        {% if messages %}
        {% for message in messages %}
        <div class="alert alert-success alert-dismissible fade show" role="alert">
          {{ message }}
          <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">×</span>
          </button>
        </div>
        {% endfor %}
        {% endif %}
        {% endwith %}
       <input type="submit" value="Register" class="form-control btn btn-primary " name="">
       <p style="padding:5px;">
       <a href="{{ url_for('login') }}" class="btn btn-dark ">Login</a></p>
       
      </div>
       
     </form>
    </div>
   </div>
  </div>
 <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>  
 </body>
</html>
templates/layout.html
//templates/layout.html
<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>{% block title %}{% endblock %}</title>
  <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css">
 <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 class="loggedin">
 <nav class="site-header sticky-top py-1">
      <div class="container d-flex flex-column flex-md-row justify-content-between">
  <a class="py-2 d-none d-md-inline-block" href="{{ url_for('home') }}"><i class="fas fa-home"></i> Home</a>
  <a class="py-2 d-none d-md-inline-block" href="{{ url_for('profile') }}"><i class="fas fa-user-circle"></i> Profile</a>
  <a class="py-2 d-none d-md-inline-block" href="{{ url_for('logout') }}"><i class="fas fa-sign-out-alt"></i> Logout</a>
   </div>
    </nav>
  
 <div class="container-fluid">
      <div class="row">
        <nav class="col-md-2 d-none d-md-block bg-light sidebar">
          <div class="sidebar-sticky">
            <ul class="nav flex-column">
              <li class="nav-item">
                <a class="nav-link active" href="#">
                  <i class="fas fa-home"></i>
                  Dashboard <span class="sr-only">(current)</span>
                </a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#">
                  <i class="fas fa-shopping-cart"></i>
                  Orders
                </a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#">
    <i class="fas fa-shopping-cart"></i>
                  Products
                </a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#">
                  <i class="fas fa-users"></i>
                  Customers
                </a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#">
                  <i class="fas fa-download"></i>
                  Reports
                </a>
              </li>
            </ul>
   </div>
        </nav>
 
        <main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
          <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom">
            <div class="col-12">
   {% block content %}{% endblock %}
   </div>
          </div>
   </main>
    
      </div>
    </div>
  
 </body>
</html>
templates/home.html
//templates/home.html
{% extends 'layout.html' %}
 
{% block title %}Home{% endblock %}
 
{% block content %}
<h1 class="h2">Dashboard</h1>
<p>Welcome back, {{ username }}!</p>
{% endblock %}
templates/profile.html
//templates/profile.html
{% extends 'layout.html' %}
 
{% block title %}Profile{% endblock %}
 
{% block content %}
<h1>Profile Page</h1>
<div>
    <p>Your account details are below:</p>
    <table>
        <tr>
            <td>Name:</td>
            <td>{{ account['fullname'] }}</td>
        </tr>
  <tr>
            <td>Username:</td>
            <td>{{ account['username'] }}</td>
        </tr>
        <tr>
            <td>Email:</td>
            <td>{{ account['email'] }}</td>
        </tr>
    </table>
</div>
{% endblock %}
static/css/style.css
//static/css/style.css
body {
  background-color: #435165;
  margin: 0;
}

.login-box
 {
  height: 50%;
  width: 30%;
  border: 1px solid grey;
  margin-left: 35%;
  margin-top: 10%;
  position: relative;
       box-shadow: 21px 12px 24px 10px rgba(0, 0, 0, .5);
       background: #dadada;
 }
 .login-header
 {
  text-align: center;
  font-family: "vardhana",cursive;
  font-size: 35px;
  background: linear-gradient(to bottom, #00bfff 0%, #5b6d7c 100%);
  color:#fff;
  position: relative;
       box-shadow: 1px 3px 14px  rgba(0, 0, 0, .5);
 }
 .login-body
 {
  padding: 20px;
  line-height: 2;
 }
.msg {
color: #721c24;
   background-color: #f8d7da;
   border-color: #f5c6cb;
padding: .75rem 1.25rem;
   margin-bottom: 1rem;
   border: 1px solid transparent;
   border-radius: .25rem;
}  
.main{
 margin-top:50px;
}

h1.title { 
font-size: 50px;
font-family: 'Passion One', cursive; 
font-weight: 400; 
}

hr{
width: 10%;
color: #fff;
}

.form-group{
margin-bottom: 15px;
}

label{
margin-bottom: 15px;
}

input,
input::-webkit-input-placeholder {
   font-size: 11px;
   padding-top: 3px;
}

.main-login{
 background-color: #fff;
   /* shadows and rounded borders */
   -moz-border-radius: 2px;
   -webkit-border-radius: 2px;
   border-radius: 2px;
   -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
   -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
   box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);

}
.form-control {
   height: auto!important;
padding: 8px 12px !important;
}
.input-group {
   -webkit-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.21)!important;
   -moz-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.21)!important;
   box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.21)!important;
}
.main-center{
 margin-top: 30px;
 margin: 0 auto;
 max-width: 400px;
   padding: 10px 40px;
background:#5b6d7c;
    color: #FFF;
   text-shadow: none;
-webkit-box-shadow: 0px 3px 5px 0px rgba(0,0,0,0.31);
-moz-box-shadow: 0px 3px 5px 0px rgba(0,0,0,0.31);
box-shadow: 0px 3px 5px 0px rgba(0,0,0,0.31);

}
span.input-group-addon i {
   color: #fff;
   font-size: 17px;padding:10px;
}

.login-button{
margin-top: 5px;
}

.login-register{
font-size: 11px;
text-align: center;
}

.site-header {
   background-color: rgba(0, 0, 0, .85);
   -webkit-backdrop-filter: saturate(180%) blur(20px);
   backdrop-filter: saturate(180%) blur(20px);
}
.site-header a { 
color:#fff;
}

Tuesday, April 27, 2021

File Generate Excel Report using Python Flask and PostgreSQL

File Generate Excel Report using Python Flask and PostgreSQL

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
);

SELECT * FROM students 

INSERT INTO students (id, fname, lname, email)
VALUES('1','cairocoders','ednalan', 'cairocoders@gmail.com');

Multiple insert
INSERT INTO
    students(id,fname,lname,email)
VALUES
    ('3','Quinn','Flynn'', 'Flynn'@gmail.com'),
    ('4','Tiger','nizon', 'nizon@gmail.com'),
    ('5','Airi','sato', 'sato@gmail.com');

ModuleNotFoundError: No module named 'xlwt'

pip install xlwt
import xlwt #pip install xlwt https://pypi.org/project/xlwt/
(venv) PS C:\flaskmyproject> pip install xlwt




app.py
#app.py
from flask import Flask, render_template, Response
import psycopg2 #pip install psycopg2 
import psycopg2.extras
import io
import xlwt #pip install xlwt https://pypi.org/project/xlwt/

app = Flask(__name__)

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('/download/report/excel')
def download_report():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    
    cur.execute("SELECT * FROM students")
    result = cur.fetchall()
    #for row in result:
    #    print(row)

    #output in bytes
    output = io.BytesIO()
    #create WorkBook object
    workbook = xlwt.Workbook()
    #add a sheet
    sh = workbook.add_sheet('Student Report')

    #add headers
    sh.write(0, 0, 'Id')
    sh.write(0, 1, 'First Name')
    sh.write(0, 2, 'Last Name')
    sh.write(0, 3, 'Email')

    idx = 0
    for row in result:
        sh.write(idx+1, 0, str(row['id']))
        sh.write(idx+1, 1, row['fname'])
        sh.write(idx+1, 2, row['lname'])
        sh.write(idx+1, 3, row['email'])
        idx += 1

    workbook.save(output)
    output.seek(0)

    return Response(output, mimetype="application/ms-excel", headers={"Content-Disposition":"attachment;filename=student_report.xls"})

if __name__ == "__main__":
    app.run(debug=True)
template/index.html
//template/index.html
<html>
<head>
    <title>File Generate Excel Report using Python Flask and PostgreSQL</title>
</head>
<body>
<h2>File Generate Excel Report using Python Flask and PostgreSQL</h2>
<p>
 <a href="{{ url_for('.download_report') }}">Generate Excel Report</a>
</p>
</body>
</html>

Python Flask Student Create, read, update and delete (CRUD) using PostgreSQL psycopg2 and dataTables bootstrap

Python Flask Student Create, read, update and delete (CRUD) using PostgreSQL psycopg2 and dataTables bootstrap

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
);

SELECT * FROM students

INSERT INTO students (id, fname, lname, email)
VALUES('1','Mark','Oto', 'Oto@gmail.com'),

Insert multiple records
INSERT INTO
    students(id,fname,lname,email)
VALUES
    ('2','Quinn','Flynn'', 'Flynn'@gmail.com'),
    ('3','Tiger','nizon', 'nizon@gmail.com'),
    ('4','Airi','sato', 'sato@gmail.com');

How to Alter Sequence in PostgreSQL

To alter the sequence so that IDs start a different number, you can't just do an update, you have to use the alter sequence command.

alter sequence students_id_seq restart with 9;

app.py
 
#app.py
from flask import Flask, render_template, request, redirect, url_for, flash
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 Index():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    s = "SELECT * FROM students"
    cur.execute(s) # Execute the SQL
    list_users = cur.fetchall()
    return render_template('index.html', list_users = list_users)

@app.route('/add_student', methods=['POST'])
def add_student():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        fname = request.form['fname']
        lname = request.form['lname']
        email = request.form['email']
        cur.execute("INSERT INTO students (fname, lname, email) VALUES (%s,%s,%s)", (fname, lname, email))
        conn.commit()
        flash('Student Added successfully')
        return redirect(url_for('Index'))

@app.route('/edit/', methods = ['POST', 'GET'])
def get_employee(id):
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
  
    cur.execute('SELECT * FROM students WHERE id = %s', (id))
    data = cur.fetchall()
    cur.close()
    print(data[0])
    return render_template('edit.html', student = data[0])

@app.route('/update/', methods=['POST'])
def update_student(id):
    if request.method == 'POST':
        fname = request.form['fname']
        lname = request.form['lname']
        email = request.form['email']
        
        cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
        cur.execute("""
            UPDATE students
            SET fname = %s,
                lname = %s,
                email = %s
            WHERE id = %s
        """, (fname, lname, email, id))
        flash('Student Updated Successfully')
        conn.commit()
        return redirect(url_for('Index'))

@app.route('/delete/', methods = ['POST','GET'])
def delete_student(id):
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
  
    cur.execute('DELETE FROM students WHERE id = {0}'.format(id))
    conn.commit()
    flash('Student Removed Successfully')
    return redirect(url_for('Index'))

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
{% extends "layout.html" %}
{% block body %}
 <div class="row"><h3>Students</h3></div>
  <div class="row">
    <div class="col-md-4">
      {% with messages = get_flashed_messages()  %}
      {% if messages %}
      {% for message in messages %}
      <div class="alert alert-success alert-dismissible fade show" role="alert">
        {{ message }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      {% endfor %}
      {% endif %}
      {% endwith %}
      <div class="card card-body">
        <form action="{{url_for('add_student')}}" method="POST">
          <div class="form-group">
            <input type="text" class="form-control" name="fname" placeholder="First Name">
          </div>
          <div class="form-group">
            <input type="text" class="form-control" name="lname" placeholder="Last Name">
          </div>
          <div class="form-group">
            <input type="email" class="form-control" name="email" placeholder="Email">
          </div>
          <button class="btn btn-primary btn-block">
            Save 
          </button>
        </form>
      </div>
    </div>
    <div class="col-md-8">
      <table id="example" class="table table-striped table-bordered" style="width:100%">
        <thead>
          <tr>
            <td>ID</td>
            <td>First Name</td>
            <td>Last Name</td>
            <td>Email</td>
            <td>Action</td>
          </tr>
        </thead>
        <tbody>
          {% for row in list_users %}
          <tr>
            <td>{{row[0]}}</td>
            <td>{{row[1]}}</td>
            <td>{{row[2]}}</td>
            <td>{{row[3]}}</td>
            <td width="130">
              <a href="/edit/{{row[0]}}" class="btn btn-secondary btn-sm">edit</a>
              <a href="/delete/{{row[0]}}" class="btn btn-danger btn-delete btn-sm">delete</a>
            </td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
  </div>
</div>
 
{% endblock %}
templates/layout.html
//templates/layout.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Python Flask Student Create, read, update and delete (CRUD) using PostgreSQL psycopg2 and dataTables bootstrap</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
 
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script>
</head>
<body>
    <nav class="navbar navbar-dark bg-dark">
      <a class="navbar-brand" href="/">Python Flask Student Create, read, update and delete (CRUD) using PostgreSQL psycopg2 and dataTables bootstrap</a>
    </nav>
 
    <div class="container pt-4">
      {% block body %}
      {% endblock %}
    </div>
  
<script>
const btnDelete= document.querySelectorAll('.btn-delete');
if(btnDelete) {
  const btnArray = Array.from(btnDelete);
  btnArray.forEach((btn) => {
    btn.addEventListener('click', (e) => {
      if(!confirm('Are you sure you want to delete it?')){
        e.preventDefault();
      }
    });
  })
}
 
$(document).ready(function() {
    $('#example').DataTable({     
      "aLengthMenu": [[3, 5, 10, 25, -1], [3, 5, 10, 25, "All"]],
        "iDisplayLength": 3
       } 
    );
} );
 
</script>
  </body>
</html>
templates/edit.html
//templates/edit.html
{% extends "layout.html" %}
{% block body %}
  <div class="row">
    <div class="col-md-4 offset-md-4">
      <div class="card card-body">
        <form action="/update/{{student.id}}" method="POST">
          <div class="form-group">
            <input type="text" name="fname" value="{{student.fname}}" class="form-control">
          </div>
          <div class="form-group">
            <input type="text" name="lname" value="{{student.lname}}" class="form-control">
          </div>
          <div class="form-group">
            <input type="text" name="email" value="{{student.email}}" class="form-control">
          </div>
          <div class="form-group">
            <button type="submit" class="btn btn-primary btn-block">
              Update
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
{% endblock %}

Python Flask PostgreSQL simple registration

Python Flask PostgreSQL simple registration

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
);

SELECT * FROM students
app.py
 
#app.py
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
                                                            #password:admin
app.config['SQLALCHEMY_DATABASE_URI']='postgresql://postgres:admin@localhost/sampledb'

db=SQLAlchemy(app)

class Student(db.Model):
  __tablename__='students'
  id=db.Column(db.Integer,primary_key=True)
  fname=db.Column(db.String(40))
  lname=db.Column(db.String(40))
  email=db.Column(db.String(40))

  def __init__(self,fname,lname,email):
    self.fname=fname
    self.lname=lname
    self.email=email

@app.route('/')
def index():
  return render_template('index.html')

@app.route('/submit', methods=['POST'])
def submit():
  fname= request.form['fname']
  lname=request.form['lname']
  email=request.form['email']

  student=Student(fname,lname,email)
  db.session.add(student)
  db.session.commit()

  #fetch a certain student
  studentResult=db.session.query(Student).filter(Student.id==1)
  for result in studentResult:
    print(result.fname)

  return render_template('success.html', data=fname)

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!doctype html>
<html>
<head>
<title>Python Flask PostgreSQL simple registration</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />	
</head>
<body >
<div class="container" >
    <div class="row" style="padding:50px;">
		<p><h1>Python Flask PostgreSQL simple registration</h1></p>
        <form action="/submit" method="POST">
            <div class="mb-3">
              <label class="form-label">First name:</label>
              <input type="text" id="fname" name="fname" class="form-control">
            </div>
            <div class="mb-3">
                <label class="form-label">Last name:</label>
                <input type="text" id="lname" name="lname" class="form-control">
            </div>
            <div class="mb-3">
                <label class="form-label">Email:</label>
                <input type="text" id="email" name="email" class="form-control">
            </div>
            <br/><br/>
            <button type="submit" class="btn btn-primary">Submit</button>
          </form>
   </div>
</div>
</body>
</html>
templates/success.html
//templates/success.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    Your data has been added successfully. Hello {{data}}!
</body>
</html>

Monday, April 26, 2021

PostgreSQL database connect in python psycopg2

PostgreSQL database connect in python psycopg2
 
#test.py
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"

import psycopg2 #pip install psycopg2 
import psycopg2.extras

conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

#cur.execute("INSERT INTO accounts (user_id, username, password, email, created_on, last_login) VALUES(%s,%s,%s,%s,%s,%s)", ("4","user2","pass2","user4@gmail.com","2021-04-01","2021-01-01"))

cur.execute("SELECT * FROM accounts;")
print(cur.fetchall())

conn.commit()
cur.close()
conn.close()

Sunday, April 25, 2021

Download Install and Setup PostgreSQL on Windows 10 create database and table

Download Install and Setup PostgreSQL on Windows 10 create database and table

PostgreSQL: The World's Most Advanced Open Source Relational Database https://www.postgresql.org/

username :admin
password : admin

SELECT * FROM accounts;

INSERT INTO accounts (user_id, username, password, email, created_on, last_login)
VALUES('1','cairocoders','pass123', 'cairocoders@gmail.com', '2021-04-01', '2021-01-01');

SELECT username
FROM accounts
ORDER BY username DESC;

SELECT
user_id,
username
FROM
accounts
ORDER BY
user_id ASC,
username DESC;

SELECT
user_id,
username
FROM
accounts
WHERE
username = 'cairocoders';

SELECT
user_id,
username,
email
FROM
accounts
WHERE
username = 'cairocoders' AND 
    email = 'cairocoders@gmail.com';

SELECT
user_id,
username,
email
FROM
accounts
WHERE
username = 'cairocoders' OR 
    email = 'cairocoders@gmail.com';

Update Multiple Selected Records using PHP Mysql and Jquery Ajax

Update Multiple Selected Records using PHP Mysql and Jquery Ajax


CREATE TABLE `employee` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `position` varchar(100) NOT NULL,
  `office` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `salary` int(11) NOT NULL,
  `photo` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `employee` (`id`, `name`, `position`, `office`, `age`, `salary`, `photo`) VALUES
(1, 'Tiger Wood', 'Accountant', 'Tokyo', 36, 5689, '01.jpg'),
(2, 'Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, 5648, '02.jpg'),
(3, 'Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, 5689, '03.jpg'),
(4, 'cylde Ednalan', 'Software Engineer', 'Olongapo', 23, 54654, '04.jpg'),
(5, 'Rhona Davidson', 'Software Engineer', 'San Francisco', 26, 5465, '05.jpg'),
(6, 'Quinn Flynn', 'Integration Specialist', 'New York', 53, 56465, '06.jpg'),
(8, 'Tiger Nixon', 'Software Engineer', 'London', 45, 456, '07.jpg'),
(9, 'Airi Satou', 'Pre-Sales Support', 'New York', 25, 4568, '08.jpg'),
(10, 'Angelica Ramos', 'Sales Assistant', 'New York', 45, 456, '09.jpg'),
(11, 'Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, 54565, '01.jpg'),
(12, 'Bradley Greer', 'Regional Director', 'San Francisco', 27, 5485, '02.jpg'),
(13, 'Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, 65468, '03.jpg'),
(14, 'Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, 354685, '04.jpg'),
(15, 'Bruno Nash', 'Customer Support', 'New York', 36, 65465, '05.jpg'),
(16, 'cairocoders', 'Sales Assistant', 'Sydney', 45, 56465, '06.jpg'),
(17, 'Zorita Serrano', 'Support Engineer', 'San Francisco', 38, 6548, '07.jpg'),
(18, 'Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, 545, '08.jpg'),
(19, 'Sakura Yamamoto', 'Support Engineer', 'Tokyo', 48, 5468, '05.jpg'),
(20, 'Serge Baldwin', 'Data Coordinator', 'Singapore', 85, 5646, '05.jpg'),
(21, 'Shad Decker', 'Regional Director', 'Tokyo', 45, 4545, '05.jpg');

ALTER TABLE `employee`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `employee`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;

index.php
//index.php
<!doctype html>
<html>
<head>
<title>Update Multiple Selected Records PHP Mysql and Jquery Ajax</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body >
<?php 
include "dbcon.php";
	$alert= "";
        if(isset($_POST['but_update'])){
            if(isset($_POST['update'])){
                foreach($_POST['update'] as $updateid){

                    $name = $_POST['name_'.$updateid];
                    $position = $_POST['position_'.$updateid];
                    $office = $_POST['office_'.$updateid];
                    $age = $_POST['age_'.$updateid];
                    $salary = $_POST['salary_'.$updateid];

                    if($name !='' && $position != '' ){
                        $updateUser = "UPDATE employee SET 
                            name='".$name."',position='".$position."'
                        WHERE id=".$updateid;
                        mysqli_query($conn,$updateUser);
                    }
                    
                }
				$alert = '<div class="alert alert-success" role="alert">Records successfully updated</div>';
            }
        }
 ?>
        <div class='container'>
			<h1>Update Multiple Selected Records using PHP Mysql and Jquery Ajax</h1>
            <form method='post' action=''><?php echo $alert; ?>
                <p><input type='submit' value='Update Selected Records' class="btn btn-success" name='but_update'></p>
				<table class="table table-bordered">
                    <tr style='background: whitesmoke;'>
                        <!-- Check/Uncheck All-->
                        <th><input type='checkbox' id='checkAll' > Check</th>
                        <th>Name</th>
                        <th>Position</th>
                        <th>Office</th>
                        <th>Age</th>
                        <th>Salary</th>
                    </tr>
                    <?php 
                    $query = "SELECT * FROM employee order by name asc limit 10";
                    $result = mysqli_query($conn,$query);

                    while($row = mysqli_fetch_array($result) ){
                        $id = $row['id'];
                        $name = $row['name'];
                        $position = $row['position'];
                        $office = $row['office'];
                        $age = $row['age'];
                        $salary = $row['salary'];
                    ?>
                        <tr>
                            <td><input type='checkbox' name='update[]' value='<?= $id ?>' ></td>
                            <td><input type='text' name='name_<?= $id ?>' value='<?= $name ?>' ></td>
                            <td><input type='text' name='position_<?= $id ?>' value='<?= $position ?>' ></td>
                            <td><input type='text' name='office_<?= $id ?>' value='<?= $office ?>' ></td>
                            <td><input type='text' name='age_<?= $id ?>' value='<?= $age ?>' ></td>
                            <td><input type='text' name='salary_<?= $id ?>' value='<?= $salary ?>' ></td>
                        </tr>
                    <?php
                    }
                    ?>
                </table>
            </form>
        </div>
        <script type="text/javascript">
            $(document).ready(function(){
                // Check/Uncheck ALl
                $('#checkAll').change(function(){
                    if($(this).is(':checked')){
                        $('input[name="update[]"]').prop('checked',true);
                    }else{
                        $('input[name="update[]"]').each(function(){
                            $(this).prop('checked',false);
                        }); 
                    }
                });
                // Checkbox click
                $('input[name="update[]"]').click(function(){
                    var total_checkboxes = $('input[name="update[]"]').length;
                    var total_checkboxes_checked = $('input[name="update[]"]:checked').length;

                    if(total_checkboxes_checked == total_checkboxes){
                        $('#checkAll').prop('checked',true);
                    }else{
                        $('#checkAll').prop('checked',false);
                    }
                });
            });
        </script>
</body>
</html>

Friday, April 23, 2021

DataTable AJAX pagination with Search using Python Flask and Mysql database

DataTable AJAX pagination with Search using Python Flask and Mysql database


CREATE TABLE `employee` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `position` varchar(100) NOT NULL,
  `office` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `salary` int(11) NOT NULL,
  `photo` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


INSERT INTO `employee` (`id`, `name`, `position`, `office`, `age`, `salary`, `photo`) VALUES
(1, 'Tiger Wood', 'Accountant', 'Tokyo', 36, 5689, '01.jpg'),
(2, 'Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, 5648, '02.jpg'),
(3, 'Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, 5689, '03.jpg'),
(4, 'cylde Ednalan', 'Software Engineer', 'Olongapo', 23, 54654, '04.jpg'),
(5, 'Rhona Davidson', 'Software Engineer', 'San Francisco', 26, 5465, '05.jpg'),
(6, 'Quinn Flynn', 'Integration Specialist', 'New York', 53, 56465, '06.jpg'),
(8, 'Tiger Nixon', 'Software Engineer', 'London', 45, 456, '07.jpg'),
(9, 'Airi Satou', 'Pre-Sales Support', 'New York', 25, 4568, '08.jpg'),
(10, 'Angelica Ramos', 'Sales Assistant', 'New York', 45, 456, '09.jpg'),
(11, 'Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, 54565, '01.jpg'),
(12, 'Bradley Greer', 'Regional Director', 'San Francisco', 27, 5485, '02.jpg'),
(13, 'Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, 65468, '03.jpg'),
(14, 'Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, 354685, '04.jpg'),
(15, 'Bruno Nash', 'Customer Support', 'New York', 36, 65465, '05.jpg'),
(16, 'cairocoders', 'Sales Assistant', 'Sydney', 45, 56465, '06.jpg'),
(17, 'Zorita Serrano', 'Support Engineer', 'San Francisco', 38, 6548, '07.jpg'),
(18, 'Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, 545, '08.jpg'),
(19, 'Sakura Yamamoto', 'Support Engineer', 'Tokyo', 48, 5468, '05.jpg'),
(20, 'Serge Baldwin', 'Data Coordinator', 'Singapore', 85, 5646, '05.jpg'),
(21, 'Shad Decker', 'Regional Director', 'Tokyo', 45, 4545, '05.jpg');

ALTER TABLE `employee`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `employee`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;

Download Datatables from here. https://datatables.net/download/

app.py
 
#app.py
from flask import Flask, request, render_template, jsonify, json
from flaskext.mysql import MySQL #pip install flask-mysql
import pymysql
 
app = Flask(__name__)
   
mysql = MySQL()
  
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'testingdb'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
 
@app.route('/')
def home():
    return render_template('index.html')

@app.route("/ajaxfile",methods=["POST","GET"])
def ajaxfile():
    try:
        conn = mysql.connect()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        if request.method == 'POST':
            draw = request.form['draw'] 
            row = int(request.form['start'])
            rowperpage = int(request.form['length'])
            searchValue = request.form["search[value]"]
            print(draw)
            print(row)
            print(rowperpage)
            print(searchValue)

            ## Total number of records without filtering
            cursor.execute("select count(*) as allcount from employee")
            rsallcount = cursor.fetchone()
            totalRecords = rsallcount['allcount']
            print(totalRecords) 

            ## Total number of records with filtering
            likeString = "%" + searchValue +"%"
            cursor.execute("SELECT count(*) as allcount from employee WHERE name LIKE %s OR position LIKE %s OR office LIKE %s", (likeString, likeString, likeString))
            rsallcount = cursor.fetchone()
            totalRecordwithFilter = rsallcount['allcount']
            print(totalRecordwithFilter) 

            ## Fetch records
            if searchValue=='':
                cursor.execute("SELECT * FROM employee ORDER BY name asc limit %s, %s;", (row, rowperpage))
                employeelist = cursor.fetchall()
            else:        
                cursor.execute("SELECT * FROM employee WHERE name LIKE %s OR position LIKE %s OR office LIKE %s limit %s, %s;", (likeString, likeString, likeString, row, rowperpage))
                employeelist = cursor.fetchall()

            data = []
            for row in employeelist:
                data.append({
                    'name': row['name'],
                    'position': row['position'],
                    'age': row['age'],
                    'salary': row['salary'],
                    'office': row['office'],
                })

            response = {
                'draw': draw,
                'iTotalRecords': totalRecords,
                'iTotalDisplayRecords': totalRecordwithFilter,
                'aaData': data,
            }
            return jsonify(response)
    except Exception as e:
        print(e)
    finally:
        cursor.close() 
        conn.close()

if __name__ == "__main__":
    app.run()
templates/index.html
//templates/index.html
<!doctype html>
<html>
<head>
<title>DataTable AJAX pagination using Python Flask and Mysql database</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />	
<link href='https://cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css' rel='stylesheet' type='text/css'>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
</head>
<body >
<div class="container" >
    <div class="row" style="padding:50px;">
		<p><h1>DataTable AJAX pagination using Python Flask and Mysql database</h1></p>
        <div >
            <table id='empTable' class='display dataTable' width='100%'>
                <thead>
                <tr>
                    <th>Employee Name</th>
                    <th>Position</th>
                    <th>Age</th>
                    <th>Salary</th>
                    <th>Office</th>
                </tr>
                </thead>
                
            </table>
        </div>
   </div>
</div>
<script>
$(document).ready(function() {

 
    var empDataTable = $('#empTable').DataTable({
                'processing': true,
                'serverSide': true,
                'serverMethod': 'post',
                'ajax': {
                    'url':'/ajaxfile'
                },
				'lengthMenu': [[5, 10, 25, 50, -1], [5, 10, 25, 50, "All"]],
                searching: true,
                sort: false,
                "serverSide": true,
                'columns': [
                    { data: 'name' },
                    { data: 'position' },
                    { data: 'age' },
                    { data: 'salary' },
                    { data: 'office' },
                ]
            });

});

</script>
</body>
</html>

Wednesday, April 21, 2021

DataTable AJAX pagination using PHP and Mysqli

DataTable AJAX pagination using PHP and Mysqli 

CREATE TABLE `employee` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `position` varchar(100) NOT NULL,
  `office` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `salary` int(11) NOT NULL,
  `photo` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


INSERT INTO `employee` (`id`, `name`, `position`, `office`, `age`, `salary`, `photo`) VALUES
(1, 'Tiger Wood', 'Accountant', 'Tokyo', 36, 5689, '01.jpg'),
(2, 'Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, 5648, '02.jpg'),
(3, 'Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, 5689, '03.jpg'),
(4, 'cylde Ednalan', 'Software Engineer', 'Olongapo', 23, 54654, '04.jpg'),
(5, 'Angelica Ramos', 'Software Engineer', 'San Francisco', 26, 5465, '05.jpg'),
(6, 'Airi Satou', 'Integration Specialist', 'New York', 53, 56465, '06.jpg'),
(8, 'Tiger Nixon', 'Software Engineer', 'London', 45, 456, '07.jpg'),
(9, 'Airi Satou', 'Pre-Sales Support', 'New York', 25, 4568, '08.jpg'),
(10, 'Angelica Ramos', 'Sales Assistant', 'New York', 45, 456, '09.jpg'),
(11, 'Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, 54565, '01.jpg'),
(12, 'Bradley Greer', 'Regional Director', 'San Francisco', 27, 5485, '02.jpg'),
(13, 'Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, 65468, '03.jpg'),
(14, 'Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, 354685, '04.jpg'),
(15, 'Bruno Nash', 'Customer Support', 'New York', 36, 65465, '05.jpg'),
(16, 'cairocoders', 'Sales Assistant', 'Sydney', 45, 56465, '06.jpg'),
(17, 'Zorita Serrano', 'Support Engineer', 'San Francisco', 38, 6548, '07.jpg'),
(18, 'Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, 545, '08.jpg');

ALTER TABLE `employee`
  ADD PRIMARY KEY (`id`);
ALTER TABLE `employee`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=19;

Download Datatables from here. https://datatables.net/download/

index.php
//index.php
<!doctype html>
<html>
<head>
<title>DataTable AJAX pagination using PHP and Mysqli</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />	
<link href='https://cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css' rel='stylesheet' type='text/css'>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
</head>
<body >
<div class="container" >
    <div class="row" style="padding:50px;">
		<p><h1>DataTable AJAX pagination using PHP and Mysqli</h1></p>
        <div >
            <table id='empTable' class='display dataTable' width='100%'>
                <thead>
                <tr>
                    <th>Employee Name</th>
                    <th>Position</th>
                    <th>Age</th>
                    <th>Salary</th>
                    <th>Office</th>
                </tr>
                </thead>
                
            </table>
        </div>
   </div>
</div>
<script>
        $(document).ready(function(){
            var empDataTable = $('#empTable').DataTable({
                'processing': true,
                'serverSide': true,
                'serverMethod': 'post',
                'ajax': {
                    'url':'ajaxfile.php'
                },
				pageLength: 5,
                'columns': [
                    { data: 'name' },
                    { data: 'position' },
                    { data: 'age' },
                    { data: 'salary' },
                    { data: 'office' },
                ]
            });
        });
</script>
</body>
</html>
ajaxfile.php
//ajaxfile.php
<?php
include('dbcon.php');
$draw = $_POST['draw'];  
$row = $_POST['start'];
$rowperpage = $_POST['length']; // Rows display per page
$columnIndex = $_POST['order'][0]['column']; // Column index
$columnName = $_POST['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
$searchValue = mysqli_real_escape_string($conn,$_POST['search']['value']); // Search value

## Search 
$searchQuery = " ";
if($searchValue != ''){
   $searchQuery .= " and (name like '%".$searchValue."%' or 
            position like '%".$searchValue."%' or 
            office like'%".$searchValue."%' ) ";
}

## Total number of records without filtering
$sel = mysqli_query($conn,"select count(*) as allcount from employee");
$records = mysqli_fetch_assoc($sel);
$totalRecords = $records['allcount'];

## Total number of records with filtering
$sel = mysqli_query($conn,"select count(*) as allcount from employee WHERE 1 ".$searchQuery);
$records = mysqli_fetch_assoc($sel);
$totalRecordwithFilter = $records['allcount'];

## Fetch records
$empQuery = "select * from employee WHERE 1 ".$searchQuery." order by ".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage;
$empRecords = mysqli_query($conn, $empQuery);

$data = array();

while($row = mysqli_fetch_assoc($empRecords)){
	$salary = $row['salary'];
	$salaryarray = "$ $salary";
    $data[] = array(
            "name"=>$row['name'],
            "position"=>$row['position'],
            "age"=>$row['age'],
            "salary"=>$salaryarray,
            "office"=>$row['office']
        );
}

## Response
$response = array(
    "draw" => intval($draw),
    "iTotalRecords" => $totalRecords,
    "iTotalDisplayRecords" => $totalRecordwithFilter,
    "aaData" => $data
);

echo json_encode($response);

?>
dbcon.php
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

Sunday, April 18, 2021

Live Editable Table using Python Flask Mysql and Jquery Ajax

Live Editable Table using Python Flask Mysql and Jquery Ajax 

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `username` varchar(255) NOT NULL,
  `name` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `users` (`id`, `username`, `name`) VALUES
(8, 'Batosai23', 'Batosai Ednalan'),
(9, 'caite', 'Caite Ednalan'),
(11, 'NarutoUzumaki', 'Naruto Uzumaki'),
(12, 'SasukeUchiha', 'Sasuke Uchiha');

ALTER TABLE `users`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21;
app.py
#app.py
from flask import Flask, request, render_template, jsonify
from flaskext.mysql import MySQL #pip install flask-mysql
import pymysql
 
app = Flask(__name__)
   
mysql = MySQL()
  
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'testingdb'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
 
@app.route('/')
def home():
    try:
        conn = mysql.connect()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        cursor.execute("SELECT * from users order by id")
        userslist = cursor.fetchall()
        return render_template('index.html',userslist=userslist)
    except Exception as e:
        print(e)
    finally:
        cursor.close() 
        conn.close()

@app.route("/update",methods=["POST","GET"])
def update():
    try:
        conn = mysql.connect()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        if request.method == 'POST':
            field = request.form['field'] 
            value = request.form['value']
            editid = request.form['id']
            
            if field == 'username':
               sql = "UPDATE users SET username=%s WHERE id=%s"
            if field == 'name':        
                sql = "UPDATE users SET name=%s WHERE id=%s"

            data = (value, editid)
            conn = mysql.connect()
            cursor = conn.cursor()
            cursor.execute(sql, data)
            conn.commit()
            success = 1
        return jsonify(success)
    except Exception as e:
        print(e)
    finally:
        cursor.close() 
        conn.close()
 
if __name__ == "__main__":
    app.run()
templates/index.html
//templates/index.html
<!doctype html>
<html>
<head>
<title>Live Editable Table using Python Flask Mysql and Jquery Ajax</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />	
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
 
 // Show Input element
 $('.edit').click(function(){
  $('.txtedit').hide();
  $(this).next('.txtedit').show().focus();
  $(this).hide();
 });

 // Save data
 $(".txtedit").focusout(function(){
  
  // Get edit id, field name and value
  var id = this.id;
  var split_id = id.split("_");
  var field_name = split_id[0];
  var edit_id = split_id[1];
  var value = $(this).val();
  
  // Hide Input element
  $(this).hide();

  // Hide and Change Text of the container with input elmeent
  $(this).prev('.edit').show();
  $(this).prev('.edit').text(value);

  $.ajax({
   url: '/update',
   type: 'post',
   data: { field:field_name, value:value, id:edit_id },
   success:function(response){
      if(response == 1){ 
         console.log('Save successfully'); 
      }else{ 
         console.log("Not saved.");  
      }
   }
  });
 
 });

});
</script>
</head>
<body >
<div class="container" >
    <div class="row" style="padding:50px;">
		<p><h1>Live Editable Table using Python Flask Mysql and Jquery Ajax</h1></p>
		<table width='100%' border='0'>
		 <tr>
		  <th width='10%'>ID</th>
		  <th width='40%'>Username</th>
		  <th width='40%'>Name</th>
		 </tr>
         {% for row in userslist %}    
		 <tr>
		  <td>{{row.id}}</td>
		  <td> 
			<div class='edit' > {{row.username}}</div> 
			<input type='text' class='txtedit' value='{{row.username}}' id='username_{{row.id}}' >
		  </td>
		  <td> 
		   <div class='edit' >{{row.name}} </div> 
		   <input type='text' class='txtedit' value='{{row.name}}' id='name_{{row.id}}' >
		  </td>
		 </tr>
         {% endfor %} 
		</table>
   </div>
</div>
<style>
.edit{
 width: 100%;
 height: 25px;
}
.editMode{
 border: 1px solid black;
}
table {
 border:3px solid lavender;
 border-radius:3px;
}
table tr:nth-child(1){
 background-color:#4285f4;
}
table tr:nth-child(1) th{
 color:white;
 padding:10px 0px;
 letter-spacing: 1px;
}
table td{
 padding:10px;
}
table tr:nth-child(even){
 background-color:lavender;
 color:black;
}
.txtedit{
 display: none;
 width: 99%;
 height: 30px;
}
</style>
</body>
</html>

Related Post