article

Friday, October 23, 2020

Flask Login using flask_login module with flask_wtf and remember me and check_password_hash

Login Flask using flask_login module with flask_wtf and remember me and check_password_hash

Database Table

CREATE TABLE user (

id INTEGER PRIMARY KEY AUTOINCREMENT,

username VARCHAR (64),

email VARCHAR (120),

password_hash VARCHAR (128)

);


install module flask_login module

ModuleNotFoundError: No module named 'flask_login' = (venv) C:\flaskmyproject>pip install flask_login


install flask_sqlalchemy module

ModuleNotFoundError: No module named 'flask_sqlalchemy' = (venv) C:\flaskmyproject>pip install Flask-SQLAlchemy


install flask_wtf module

pip install Flask-WTF


app.py



#app.py
from flask import Flask, render_template, flash, redirect, url_for
from flask_sqlalchemy import SQLAlchemy 
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
#ModuleNotFoundError: No module named 'flask_sqlalchemy' = (venv) C:\flaskmyproject>pip install Flask-SQLAlchemy
#ModuleNotFoundError: No module named 'flask_login' = (venv) C:\flaskmyproject>pip install flask_login
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired
from werkzeug.security import generate_password_hash, check_password_hash

#import sqlite3
 
app = Flask(__name__)
#conn = sqlite3.connect('flask_login.db')
#print("Opened database successfully");

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///flask_login.db'
app.config['SECRET_KEY'] = 'cairocoders-ednalan'
 
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)

class LoginForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    remember_me = BooleanField('Remember Me')
    submit = SubmitField('Sign In')

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))
 
    def __repr__(self):
        return ''.format(self.username)  
   
    def set_password(self, password):
        self.password_hash = generate_password_hash(password)
 
    def check_password(self, password):
        return check_password_hash(self.password_hash, password)
	
@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

@login_manager.unauthorized_handler
def unauthorized_callback():
    return redirect('/login')
	
@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('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('Invalid username or password')
            return redirect(url_for('login'))
        login_user(user, remember=form.remember_me.data)
        return redirect(url_for('index'))
    return render_template('login.html', title='Sign In', form=form)
	
@app.route('/home')
@login_required
def home():
    return 'The current user is ' + current_user.username 	

@app.route('/profile')
@login_required
def profile():
    return render_template('profile.html')
	
@app.route('/logout')
@login_required
def logout():
    logout_user()
    return 'You are now logged out!'
	
if __name__ == '__main__':
 app.run(debug=True)
 
templates/login.html
//templates/login.html
<html lang="en">
<head>
<title>Login</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 text-white pt-5">Login Flask using flask_login module with flask_wtf and remember me and check_password_hash</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 id="login-form" class="form" action="" method="post" novalidate>
					{{ form.hidden_tag() }}
					<div class="form-group">
						{{ form.username.label }}<br>
						{{ form.username(size=32, class_="form-control") }}
						{% for error in form.username.errors %}
						<span style="color: red;">[{{ error }}]</span>
						{% endfor %}
					</div>
					<div class="form-group">
						{{ form.password.label }}<br>
						{{ form.password(size=32, class_="form-control") }}
						{% for error in form.password.errors %}
						<span style="color: red;">[{{ error }}]</span>
						{% endfor %}
					</div>
					<p>{{ form.remember_me() }} {{ form.remember_me.label }}</p>
					<p>{{ form.submit(class_="btn btn-success") }}</p>
			</form>
				</div>
                </div>
            </div>
        </div>
    </div>
<style>
body {
  margin: 0;
  padding: 0;
  background-color: #17a2b8;
}
#login .container #login-row #login-column #login-box {
  margin-top: 120px;
  max-width: 600px;
  height: 350px;
  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>
templates/index.html
//templates/index.html
<html lang="en">
    <head>
        <meta charset="utf-8">
		<title>Index</title>
    </head>
    <body>
<div>
    <a href="{{ url_for('index') }}">Home</a>
    {% if current_user.is_anonymous %}
    <a href="{{ url_for('login') }}">Login</a>
    {% else %}
    <a href="{{ url_for('logout') }}">Logout</a>
    {% endif %}
</div>
<h1>Hi, {{ current_user.username }}!</h1>
<p>password hash, {{ hash }}</p>
<p>check password hash, {{ check_hash }}</p>
    </body>
</html>
templates/profile.html
//templates/profile.html
<html lang="en">
    <head>
        <meta charset="utf-8">
		<title>profile</title>
    </head>
    <body>
<div>
    <a href="{{ url_for('index') }}">Home</a>
    {% if current_user.is_anonymous %}
    <a href="{{ url_for('login') }}">Login</a>
    {% else %}
    <a href="{{ url_for('logout') }}">Logout</a>
    {% endif %}
</div>
<h1>Hi, {{ current_user.username }}!</h1>
    </body>
</html>

Sunday, October 18, 2020

How to upload and resize image in PHP

How to upload and resize image in PHP
upload_resize.html
//upload_resize.html
<!DOCTYPE html>
<html>
<head>
<title>How to upload and resize image in PHP</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$(document).ready( function() {
		function readURL(input) {
		    if (input.files && input.files[0]) {
		        var reader = new FileReader();
		        reader.onload = function (e) {
		            $('#img-upload').attr('src', e.target.result);
		        }
		        reader.readAsDataURL(input.files[0]);
		    }
		}
		$("#imgInp").change(function(){
		    readURL(this);
		}); 	
});
</script>
</head>
<body>
<style>
.btn-file {
    position: relative;
    overflow: hidden;
}
.btn-file input[type=file] {
    position: absolute;
    top: 0;
    right: 0;
    min-width: 100%;
    min-height: 100%;
    font-size: 100px;
    text-align: right;
    filter: alpha(opacity=0);
    opacity: 0;
    outline: none;
    background: white;
    cursor: inherit;
    display: block;
}
#img-upload{
    width: 100%;
}
</style>
<div class="container">
<div class="col-md-6"><p><h3>How to upload and resize image in PHP</h3></p>
	<form action="upload.php" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label>Upload Image</label>
        <div class="input-group">
            <span class="input-group-btn">
                <span class="btn btn-default btn-file">
                    Browse <input type="file" name="image" id="imgInp">
                </span>
            </span>
            <input type="text" class="form-control" readonly>
        </div>
        <img id='img-upload'/>
    </div>
	<div class="form-group">
	<input type="submit" name="submit" value="Submit" class="btn btn-primary"/>
	</div>
	</form>
</div>
</div>
</body>
</html>
upload.php
//upload.php
<?php
if(isset($_POST["submit"])) {
    if(is_array($_FILES)) {
        $file = $_FILES['image']['tmp_name']; 
        $sourceProperties = getimagesize($file);
        $fileNewName = time();
        $folderPath = "upload/";
        $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        $imageType = $sourceProperties[2];
        switch ($imageType) {
            case IMAGETYPE_PNG:
                $imageResourceId = imagecreatefrompng($file); 
                $targetLayer = imageResize($imageResourceId,$sourceProperties[0],$sourceProperties[1]);
                imagepng($targetLayer,$folderPath. $fileNewName. "_thump.". $ext);
                break;
            case IMAGETYPE_GIF:
                $imageResourceId = imagecreatefromgif($file); 
                $targetLayer = imageResize($imageResourceId,$sourceProperties[0],$sourceProperties[1]);
                imagegif($targetLayer,$folderPath. $fileNewName. "_thump.". $ext);
                break;
            case IMAGETYPE_JPEG:
                $imageResourceId = imagecreatefromjpeg($file); 
                $targetLayer = imageResize($imageResourceId,$sourceProperties[0],$sourceProperties[1]);
                imagejpeg($targetLayer,$folderPath. $fileNewName. "_thump.". $ext);
                break;
            default:
                echo "Invalid Image type.";
                exit;
                break;
        }
        move_uploaded_file($file, $folderPath. $fileNewName. ".". $ext);
        echo "Image Resize Successfully.";
    }
}
function imageResize($imageResourceId,$width,$height) {
    $targetWidth =340;
    $targetHeight =339;
    $targetLayer=imagecreatetruecolor($targetWidth,$targetHeight);
    imagecopyresampled($targetLayer,$imageResourceId,0,0,0,0,$targetWidth,$targetHeight, $width,$height);
    return $targetLayer;
}
?>

Saturday, October 17, 2020

How to create Flask SQLite Database

 



How to create Flask SQLite Database
Python has built-in support for SQLite. The SQlite3 module comes with the Python release.
In this article you will learn how the Flask application interacts with SQLite.
#app.py
from flask import Flask
import sqlite3

app = Flask(__name__)

conn = sqlite3.connect('database.db')
print("Opened database successfully");

conn.execute('CREATE TABLE students (name TEXT, addr TEXT, city TEXT, pin TEXT)')
print ("Table created successfully");
conn.close()

if __name__ == '__main__':
   app.run(debug = True)

Friday, October 16, 2020

Simple Flask Login

Simple Flask Login
Flask-Login module It provides user session management for Flask: logging in, logging out, and remembering session. 

The module stores the user ID, restricts views to logged in users, protects cookies and has many other features.
https://flask-login.readthedocs.io/en/latest/
app.py
from flask import Flask, redirect
from flask_sqlalchemy import SQLAlchemy 
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
#ModuleNotFoundError: No module named 'flask_sqlalchemy' = (venv) C:\flaskmyproject>pip install Flask-SQLAlchemy
#ModuleNotFoundError: No module named 'flask_login' = (venv) C:\flaskmyproject>pip install flask_login

#import sqlite3
 
app = Flask(__name__)
#conn = sqlite3.connect('flask_login.db')
#print("Opened database successfully");

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///flask_login.db'
app.config['SECRET_KEY'] = 'cairocoders-ednalan'
 
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(30), unique=True)
	
@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

@login_manager.unauthorized_handler
def unauthorized_callback():
    return redirect('/login')
	
@app.route('/')
def index():
    return 'Public Page'
	
@app.route('/login')
def login():
    user = User.query.filter_by(username='cairocoders').first()
    login_user(user)
    return 'You are now logged in!'	
	
@app.route('/home')
@login_required
def home():
    return 'The current user is ' + current_user.username 	

@app.route('/profile')
@login_required
def profile():
    return 'profile page'
	
@app.route('/logout')
@login_required
def logout():
    logout_user()
    return 'You are now logged out!'
	
if __name__ == '__main__':
 app.run(debug=True)
 

Simple Jquery Ajax and jsonify

 


Simple Jquery Ajax and jsonify
#app.py
from flask import Flask, render_template, jsonify

app = Flask(__name__)

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

@app.route('/_get_data/', methods=['POST'])
def _get_data():
    myList = ['Element1', 'Element2', 'Element3']

    return jsonify({'data': render_template('response.html', myList=myList)})

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <button id="btn">Click Me</button>
        <div id="response"></div>
        <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
  <script type="text/javascript">
      $('button#btn').click(function(){
        $.ajax({
            url: "/_get_data/",
            type: "POST",
            success: function(resp){
                $('div#response').append(resp.data);
            }
        });
      });
  </script>
    </body>
</html>
templates/response.html
//templates/response.html
<ul>
    {% for elem in myList %}
        <li>{{elem}}</li>
    {% endfor %}
</ul>

Thursday, October 15, 2020

Flask Jquery ajax upload image with blueimp jQuery-File-Upload, jQuery Templates and MySQLdb Database

 

Flask Jquery ajax upload image with blueimp jQuery-File-Upload, jQuery Templates and MySQLdb Database

Database Table
CREATE TABLE `tbl_blog` (
  `blog_id` int(11) NOT NULL,
  `blog_title` varchar(200) NOT NULL,
  `blog_description` text NOT NULL,
  `blog_user_id` int(11) NOT NULL,
  `blog_date` datetime NOT NULL,
  `blog_file_path` varchar(200) NOT NULL,
  `blog_accomplished` int(11) NOT NULL,
  `blog_private` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

app.py
#app.py
from flask import Flask, render_template, json, request, redirect, session, jsonify
from flask_mysqldb import MySQL,MySQLdb #pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb
from datetime import datetime
import os
import uuid

app = Flask(__name__)

app.secret_key = "caircocoders-ednalan-2020"

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'flaskdb'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)
app.config['UPLOAD_FOLDER'] = 'static/Uploads' #templates/static/Uploads/

@app.route('/')
def main():
    return redirect('/userHome')
	
@app.route('/userHome')
def userHome():
    session['sessionusername'] = "cairocoders@gmail.com"
    print(session.get('sessionusername'))	
    if session.get('sessionusername'):
        return render_template('userHome.html')
    else:
        return render_template('error.html',error = 'Unauthorized Access')

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST':
        file = request.files['file']
        extension = os.path.splitext(file.filename)[1]
        f_name = str(uuid.uuid4()) + extension
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], f_name))
    return json.dumps({'filename':f_name})
	
@app.route('/addBlog', methods=['GET', 'POST'])
def addBlog():
    now = datetime.now()
    print("now =", now)
    if request.method == 'POST':
        _title = request.form['inputTitle']
        _description = request.form['inputDescription']
        _user = session.get('sessionusername')
        # validate the received values
        if _title and _description:
            if request.form.get('filePath') is None:
                _filePath = ''
            else:
                _filePath = request.form.get('filePath')
            if request.form.get('private') is None:
                _private = 0
            else:
                _private = 1
            if request.form.get('done') is None:
                _done = 0
            else:
                _done = 1
				
            cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
            result = cur.execute("SELECT * FROM users WHERE email = %s", [_user])
            print(result)			
            if result > 0:
                data = cur.fetchone()
                blog_user_id = data['id']
                cur.execute("INSERT INTO tbl_blog (blog_title, blog_description, blog_user_id, blog_date, blog_file_path, blog_accomplished, blog_private) VALUES (%s,%s,%s,%s,%s,%s,%s)",(_title,_description,blog_user_id,now,_filePath,_private,_done,))
                mysql.connection.commit()
                cur.close()
                return redirect('/userHome')
            else:
                error = 'Invalid login'
                return render_template('addBlog.html', error=error)
        else:
            error = 'Enter the required fields'
            return render_template('addBlog.html', error=error)
			
    return render_template('addBlog.html')

@app.route('/getBlog')
def getBlog():
    if session.get('sessionusername'):
        _user = '12'
        cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        result = cur.execute("SELECT * FROM tbl_blog WHERE blog_user_id = %s", [_user])
        blogs = cur.fetchall()
        blogs_dict = []
        for blog in blogs:
            blog_dict = {
                    'Id': blog['blog_id'],
                    'Title': blog['blog_title'],
                    'Description': blog['blog_description'],
                    'Date': blog['blog_date']}
            blogs_dict.append(blog_dict)
        return json.dumps(blogs_dict)
    else:
        print("error getblog")
        return render_template('error.html', error = 'Unauthorized Access')
     
@app.route('/getBlogById',methods=['GET', 'POST'])
def getBlogById():
    if session.get('sessionusername'):
        _id = request.form['id']
        cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        result = cur.execute("SELECT * FROM tbl_blog WHERE blog_id = %s", [_id])
        blogs = cur.fetchall()
        blogs_dict = []
        for blog in blogs:
            blog_dict = {
                    'Id': blog['blog_id'],
                    'Title': blog['blog_title'],
                    'Description': blog['blog_description'],
                    'FilePath': blog['blog_file_path'],
                    'Done': blog['blog_accomplished'],
                    'Private': blog['blog_private']}
            blogs_dict.append(blog_dict)
        return json.dumps(blogs_dict)
    else:
        return render_template('error.html', error = 'Unauthorized Access')
 
@app.route('/updateBlog', methods=['POST'])
def updateBlog():
    if session.get('sessionusername'):
        _title = request.form['title']
        _description = request.form['description']
        _blog_id = request.form['id']
        cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cur.execute("""
            UPDATE tbl_blog
            SET blog_title = %s,
                blog_description = %s
            WHERE blog_id = %s
        """, (_title, _description, _blog_id))
        mysql.connection.commit()
        cur.close()
        return json.dumps({'status':'OK'})
    else:
        return render_template('error.html', error = 'Unauthorized Access')
 
@app.route('/deleteBlog',methods=['POST'])
def deleteBlog():
    if session.get('sessionusername'):
        _id = request.form['id']
        _user = session.get('user')
        cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cur.execute('DELETE FROM tbl_blog WHERE blog_id = {0}'.format(_id))
        mysql.connection.commit()
        cur.close()
        return json.dumps({'status':'OK'})
    else:
        return render_template('error.html', error = 'Unauthorized Access')
		
if __name__ == '__main__':
    app.run(debug=True)
templates/addBlog.html
File upload via blueimp jQuery-File-Upload
https://github.com/blueimp/jQuery-File-Upload
Extract the source and add the following script references to addBlog.html
src="/static/js/jquery.fileupload.js
src="/static/js/jquery.fileupload-process.js
src="/static/js/jquery.fileupload-ui.js
//templates/addBlog.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Add Blog</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>
<script src="/static/js/jquery.ui.widget.js"></script>
<script type="text/javascript" src="/static/js/jquery.fileupload.js"></script>
<script type="text/javascript" src="/static/js/jquery.fileupload-process.js"></script>
<script type="text/javascript" src="/static/js/jquery.fileupload-ui.js"></script>
<script>
$(function(){
    $('#fileupload').fileupload({
        url: 'upload',
                dataType: 'json',
                add: function (e, data) {
                  data.submit();
                },
                success:function(response,status) {
                  console.log(response.filename);
                  var filePath = 'static/Uploads/' + response.filename;
                  $('#imgUpload').attr('src',filePath);
                  $('#filePath').val(filePath);
                  console.log('success');
                },
                error:function(error){
                        console.log(error);
                }
    });
})
</script>
<style>
        .btn-file {
            position: relative;
            overflow: hidden;
        }
        .btn-file input[type=file] {
            position: absolute;
            top: 0;
            right: 0;
            min-width: 100%;
            font-size: 100px;
            text-align: right;
            filter: alpha(opacity=0);
            opacity: 0;
            outline: none;
            background: white;
            cursor: inherit;
            display: block;
        }
    </style>
</head>
<body>
    <div class="container" style="padding:20px;">
        <div class="header">
            <nav>
                <ul class="nav nav-pills pull-right">
                    <li role="presentation" class="active"><a href="/userHome">Dashboard</a></li>
                    <li role="presentation"><a href="/addBlog">Add Blog</a></li>
                    <li role="presentation"><a href="/logout">Log Out</a></li>
                </ul>
            </nav>
            <img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ > 
        </div>
<section>
        <form role="form" method="post" action="/addBlog">
            <legend>Create Your Blog Post</legend>
            <div class="form-group">
                <label for="txtTitle">Title</label>
                <input id="txtTitle" name="inputTitle" type="text" placeholder="placeholder" class="form-control input-md">
            </div>
            <div class="form-group">
                <label for="txtPost">Description</label>
                <textarea class="form-control" id="txtPost" name="inputDescription"></textarea>
            </div>
            <div class="form-group">
              <label for="txtPost">Photos</label>
              <div class="input-group">
                <span class="input-group-btn">
                  <span class="btn btn-primary btn-file">
                      Browse… <input type="file" id="fileupload" name="file" multiple>
                  </span>
                </span>
                <div class="pull-right">
                  <img id="imgUpload" style="width: 140px; height: 140px;" class="img-thumbnail"><input type="hidden" name="filePath" id="filePath"></input>
                </div>
              </div>
            </div>
            <div class="form-group">
                <label>Mark this as private and not visible to others.</label>
                <br/>
                <input type="checkbox" name="private"> Mark as Private <span class="glyphicon glyphicon-lock" aria-hidden="true"></span>
            </div>
            <div class="form-group">
                <label>Have you already accomplished this?</label>
                <br/>
                <input type="checkbox" name="done"> Mark as Done <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
            </div>
            <div class="form-group">
                <p class="text-center">
                    <input id="singlebutton" name="singlebutton" class="btn btn-primary" type="submit" value="Publish" />
                </p>
            </div>
        </form>
</section>
        <footer class="footer">
            <p>©tutorial101.blogspot.com</p>
        </footer>
    </div>
  </body>
</html>
templates/userHome.html
//templates/userHome.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Flask Jquery ajax upload image with blueimp jQuery-File-Upload, jQuery Templates and MySQLdb Database</title>
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css">
<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>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>
<script>
      $(function(){   
          $('#btnUpdate').click(function(){
            $.ajax({
              url : '/updateBlog',
              data : {title:$('#editTitle').val(),description:$('#editDescription').val(),id:localStorage.getItem('editId')},
              type : 'POST',
              success: function(res){       
                $('#editModal').modal('hide');  
                // Re populate the grid                
                GetBlogs();         
              },
              error: function(error){
                console.log(error);
              }
            });
          });
      });
	  
      function GetBlogs(){
        $.ajax({
          url : '/getBlog',
          type : 'GET',
          success: function(res){             
            var blogObj = JSON.parse(res);
            $('#ulist').empty();
            $('#listTemplate').tmpl(blogObj).appendTo('#ulist');        
          },
          error: function(error){
            console.log(error);
          }
        });
      }

      // get blog posts from db when the user signed in
      $(function() {
          $.ajax({
              url: '/getBlog',
              type: 'GET',
              success: function(res) {
   
                  // Parse the JSON response
                  var blogObj = JSON.parse(res);
                   
                  // Append to the template
                  $('#listTemplate').tmpl(blogObj).appendTo('#ulist');
     
              },
              error: function(error) {
                  console.log(error);
              }
          });
      });


      function Edit(elm) {
          localStorage.setItem('editId',$(elm).attr('data-id'));
          $.ajax({
              url: '/getBlogById',
              data: {
                  id: $(elm).attr('data-id')
              },
              type: 'POST',
              success: function(res) {
                var data = JSON.parse(res);
                console.log(data);
                $('#editTitle').val(data[0]['Title']);
                $('#editDescription').val(data[0]['Description']);
                $('#imgUpload').attr('src',data[0]['FilePath']);
                if(data[0]['Private']=="1"){
                  $('#chkPrivate').attr('checked','checked');
                }
                if(data[0]['Done']=="1"){
                  $('#chkDone').attr('checked','checked');
                }
                $('#editModal').modal('show');
              },
              error: function(error) {
                  console.log(error);
              }
          });
      }
      function ConfirmDelete(elm){
        localStorage.setItem('deleteId',$(elm).attr('data-id'));
        $('#deleteModal').modal('show');
      }
      function Delete(){
        $.ajax({
          url : '/deleteBlog',
          data : {id:localStorage.getItem('deleteId')},
          type : 'POST',
          success: function(res){
            var result = JSON.parse(res);
            if(result.status == 'OK'){
              $('#deleteModal').modal('hide');
              GetBlogs();
            }
            else{
              alert(result.status); 
            }
          },
          error: function(error){
            console.log(error);
          }
        });
      }
</script>
<style>
    .trash {
            color: rgb(209, 91, 71);
    }
    .panel-body .checkbox {
            display: inline-block;
            margin: 0px;
    }
    .list-group {
            margin-bottom: 0px;
    }
</style>   
</head>
<body>
    <div class="container" style="padding:20px;">
        <div class="header">
            <nav>
                <ul class="nav nav-pills pull-right">
                    <li role="presentation" class="active"><a href="/userHome">Dashboard</a></li>
                    <li role="presentation"><a href="/addBlog">Add Blog</a></li>
                    <li role="presentation"><a href="/logout">Log Out</a></li>
                </ul>
            </nav>
            <img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ > 
        </div>
	<p><h4>Flask Jquery ajax upload image with blueimp jQuery-File-Upload, jQuery Templates and MySQLdb Database</h4></p>	
      <script id="listTemplate" type="text/x-jQuery-tmpl">
          <li class="list-group-item">
              <div class="checkbox">
                  <label>
                      ${Title}
                  </label>
              </div>
              <div class="pull-right action-buttons">
                  <a data-id=${Id} onclick="Edit(this)"><span class="glyphicon glyphicon-pencil"></span></a>     
                  <a data-id=${Id} onclick="ConfirmDelete(this)"><span class="glyphicon glyphicon-trash"></span></a> 
              </div>
          </li>
      </script>
      <div class="row">
        <div class="col-md-12">            
            <div class="panel-body">
              <ul id="ulist" class="list-group">                                                 
              </ul>
            </div>             
        </div>
      </div>

      <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
              <h4 class="modal-title" id="editModalLabel">Update Blog</h4>
            </div>
            <div class="modal-body">
              <form role="form">
                <div class="form-group">
                  <label for="recipient-name" class="control-label">Title:</label>
                  <input type="text" class="form-control" id="editTitle">
                </div>
                <div class="form-group">
                  <label for="message-text" class="control-label">Description:</label>
                  <textarea class="form-control" id="editDescription"></textarea>
                </div>

                <div class="form-group">
                  <label for="txtPost">Photos</label>
                                 
                  <div class="input-group">
                    <span class="input-group-btn">
                      <span class="btn btn-primary btn-file">
                            Browse… <input type="file" id="fileupload" name="file" multiple>
                      </span>
                    </span>
                    <div class="pull-right">
                      <img id="imgUpload" style="width: 140px; height: 140px;" class="img-thumbnail"><input type="hidden" name="filePath" id="filePath"></input>
                    </div>
                  </div> 
                </div>

                <div class="form-group">
                  <label>Mark this as private and not visible to others.</label><br/>
                  <input id="chkPrivate" name="private" type="checkbox"> Mark as Private <span class="glyphicon glyphicon-lock" aria-hidden="true"></span>
                </div>

                <div class="form-group">
                  <label>Have you already accomplished this?</label><br/>
                  <input id="chkDone" name="done" type="checkbox"> Mark as Done <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
                </div>
             </form>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
              <button id="btnUpdate" type="button" class="btn btn-primary">Update</button>
            </div>
          </div>
        </div>
      </div>
      <div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header" style="text-align:center;">
              <h4 class="modal-title" style="color:red;" id="deleteModalLabel">You are going to Delete this forever !!</h4>
            </div>
           
            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
              <button type="button" class="btn btn-primary" onclick="Delete()">Delete</button>
            </div>
          </div>
        </div>
      </div>
        <footer class="footer">
            <p>©tutorial101.blogspot.com</p>
        </footer>
    </div>
</body>
</html>

Wednesday, October 14, 2020

Flask Add Edit Delete with Jquery ajax, jQuery Templates and MySQLdb Database

 


Flask Add Edit Delete with Jquery ajax, jQuery Templates and MySQLdb Database

Database Table

CREATE TABLE `tbl_blog` (

  `blog_id` int(11) NOT NULL,

  `blog_title` varchar(200) NOT NULL,

  `blog_description` text NOT NULL,

  `blog_user_id` int(11) NOT NULL,

  `blog_date` datetime NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=latin1;



app.py
#app.py
from flask import Flask, render_template, json, request, redirect, session, jsonify
from flask_mysqldb import MySQL,MySQLdb #pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb
from datetime import datetime

app = Flask(__name__)

app.secret_key = "caircocoders-ednalan-2020"

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'flaskdb'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)

@app.route('/')
def main():
    return redirect('/userHome')

@app.route('/userHome')
def userHome():
    session['sessionusername'] = "cairocoders@gmail.com"
    print(session.get('sessionusername'))	
    if session.get('sessionusername'):
        return render_template('userHome.html')
    else:
        return render_template('error.html',error = 'Unauthorized Access')

@app.route('/addBlog', methods=['GET', 'POST'])
def addBlog():
    now = datetime.now()
    print("now =", now)
    if request.method == 'POST':
        _title = request.form['inputTitle']
        _description = request.form['inputDescription']
        _user = session.get('sessionusername')
        # validate the received values
        if _title and _description:
            cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
            result = cur.execute("SELECT * FROM users WHERE email = %s", [_user])
            print(result)			
            if result > 0:
                data = cur.fetchone()
                blog_user_id = data['id']
                cur.execute("INSERT INTO tbl_blog (blog_title, blog_description, blog_user_id, blog_date) VALUES (%s,%s,%s,%s)",(_title,_description,blog_user_id,now,))
                mysql.connection.commit()
                cur.close()
                return redirect('/userHome')
            else:
                error = 'Invalid login'
                return render_template('addBlog.html', error=error)
        else:
            error = 'Enter the required fields'
            return render_template('addBlog.html', error=error)
			
    return render_template('addBlog.html')

@app.route('/getBlog')
def getBlog():
    if session.get('sessionusername'):
        #_user = session.get('sessionusername')
        _user = '12'
        cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        result = cur.execute("SELECT * FROM tbl_blog WHERE blog_user_id = %s", [_user])
        blogs = cur.fetchall()
        blogs_dict = []
        for blog in blogs:
            blog_dict = {
                    'Id': blog['blog_id'],
                    'Title': blog['blog_title'],
                    'Description': blog['blog_description'],
                    'Date': blog['blog_date']}
            blogs_dict.append(blog_dict)
        return json.dumps(blogs_dict)
    else:
        print("error getblog")
        return render_template('error.html', error = 'Unauthorized Access')
	
@app.route('/getBlogById',methods=['GET', 'POST'])
def getBlogById():
    if session.get('sessionusername'):
        _id = request.form['id']
        cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        result = cur.execute("SELECT * FROM tbl_blog WHERE blog_id = %s", [_id])
        blogs = cur.fetchall()
        blogs_dict = []
        for blog in blogs:
            blog_dict = {
                    'Id': blog['blog_id'],
                    'Title': blog['blog_title'],
                    'Description': blog['blog_description']}
            blogs_dict.append(blog_dict)
        return json.dumps(blogs_dict)
    else:
        return render_template('error.html', error = 'Unauthorized Access')

@app.route('/updateBlog', methods=['POST'])
def updateBlog():
    if session.get('sessionusername'):
        _title = request.form['title']
        _description = request.form['description']
        _blog_id = request.form['id']
        cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cur.execute("""
            UPDATE tbl_blog
            SET blog_title = %s,
                blog_description = %s
            WHERE blog_id = %s
        """, (_title, _description, _blog_id))
        mysql.connection.commit()
        cur.close()
        return json.dumps({'status':'OK'})
    else:
        return render_template('error.html', error = 'Unauthorized Access')

@app.route('/deleteBlog',methods=['POST'])
def deleteBlog():
    if session.get('sessionusername'):
        _id = request.form['id']
        _user = session.get('user')
        cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cur.execute('DELETE FROM tbl_blog WHERE blog_id = {0}'.format(_id))
        mysql.connection.commit()
        cur.close()
        return json.dumps({'status':'OK'})
    else:
        return render_template('error.html', error = 'Unauthorized Access')
		
if __name__ == '__main__':
    app.run(debug=True)
templates/userHome.html
Binding retrieved data to html via JQuery templates
url for uquery templates https://github.com/BorisMoore/jquery-tmpl
http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js
bind data inside the ul with class list-group
//templates/userHome.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Flask Add Edit Delete with Jquery ajax, jQuery Templates and MySQLdb Database</title>
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css">
<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>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>
<script>
      $(function(){   
          $('#btnUpdate').click(function(){
            $.ajax({
              url : '/updateBlog',
              data : {title:$('#editTitle').val(),description:$('#editDescription').val(),id:localStorage.getItem('editId')},
              type : 'POST',
              success: function(res){       
                $('#editModal').modal('hide');  
                // Re populate the grid                
                GetBlogs();         
              },
              error: function(error){
                console.log(error);
              }
            });
          });
      });
	  
      function GetBlogs(){
        $.ajax({
          url : '/getBlog',
          type : 'GET',
          success: function(res){             
            var blogObj = JSON.parse(res);
            $('#ulist').empty();
            $('#listTemplate').tmpl(blogObj).appendTo('#ulist');        
          },
          error: function(error){
            console.log(error);
          }
        });
      }

      // get blog posts from db when the user signed in
      $(function() {
          $.ajax({
              url: '/getBlog',
              type: 'GET',
              success: function(res) {
   
                  // Parse the JSON response
                  var blogObj = JSON.parse(res);
                   
                  // Append to the template
                  $('#listTemplate').tmpl(blogObj).appendTo('#ulist');
     
              },
              error: function(error) {
                  console.log(error);
              }
          });
      });


      function Edit(elm) { 
          localStorage.setItem('editId',$(elm).attr('data-id'));
          $.ajax({
              url: '/getBlogById',
              data: {
                  id: $(elm).attr('data-id')
              },
              type: 'POST',
              success: function(res) {
                // Parse the received JSON string
                var data = JSON.parse(res);

                //Populate the Pop up
                $('#editTitle').val(data[0]['Title']);
                $('#editDescription').val(data[0]['Description']);
                 
                // Trigger the Pop Up
                $('#editModal').modal('show');
              },
              error: function(error) {
                  console.log(error);
              }
          });
      }
      function ConfirmDelete(elm){
        localStorage.setItem('deleteId',$(elm).attr('data-id'));
        $('#deleteModal').modal('show');
      }
      function Delete(){
        $.ajax({
          url : '/deleteBlog',
          data : {id:localStorage.getItem('deleteId')},
          type : 'POST',
          success: function(res){
            var result = JSON.parse(res);
            if(result.status == 'OK'){
              $('#deleteModal').modal('hide');
              GetBlogs();
            }
            else{
              alert(result.status); 
            }
          },
          error: function(error){
            console.log(error);
          }
        });
      }
</script>
<style>
    .trash {
            color: rgb(209, 91, 71);
    }
    .panel-body .checkbox {
            display: inline-block;
            margin: 0px;
    }
    .list-group {
            margin-bottom: 0px;
    }
</style>   
</head>
<body>
    <div class="container">
        <div class="header">
            <nav>
                <ul class="nav nav-pills pull-right">
                    <li role="presentation" class="active"><a href="/userHome">Dashboard</a></li>
                    <li role="presentation"><a href="/addBlog">Add Blog</a></li>
                    <li role="presentation"><a href="/logout">Log Out</a></li>
                </ul>
            </nav>
            <img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ > 
        </div>
      <script id="listTemplate" type="text/x-jQuery-tmpl">
          <li class="list-group-item">
              <div class="checkbox">
                  <label>
                      ${Title}
                  </label>
              </div>
              <div class="pull-right action-buttons">
                  <a data-id=${Id} onclick="Edit(this)"><span class="glyphicon glyphicon-pencil"></span></a>     
                  <a data-id=${Id} onclick="ConfirmDelete(this)"><span class="glyphicon glyphicon-trash"></span></a> 
              </div>
          </li>
      </script>
      <div class="row">
        <div class="col-md-12">            
            <div class="panel-body">
              <ul id="ulist" class="list-group">                                                 
              </ul>
            </div>             
        </div>
      </div>

      <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
              <h4 class="modal-title" id="editModalLabel">Update Blog</h4>
            </div>
            <div class="modal-body">
              <form role="form">
                <div class="form-group">
                  <label for="recipient-name" class="control-label">Title:</label>
                  <input type="text" class="form-control" id="editTitle">
                </div>
                <div class="form-group">
                  <label for="message-text" class="control-label">Description:</label>
                  <textarea class="form-control" id="editDescription"></textarea>
                </div>
              </form>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
              <button id="btnUpdate" type="button" class="btn btn-primary">Update</button>
            </div>
          </div>
        </div>
      </div>

      <div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header" style="text-align:center;">
              <h4 class="modal-title" style="color:red;" id="deleteModalLabel">You are going to Delete this forever !!</h4>
            </div>
           
            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
              <button type="button" class="btn btn-primary" onclick="Delete()">Delete</button>
            </div>
          </div>
        </div>
      </div>
        <footer class="footer">
            <p>©tutorial101.blogspot.com</p>
        </footer>
    </div>
</body>
</html>
templates/error.html
//templates/error.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Unauthorized Access</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">
        <div class="header">
            <nav>
                <ul class="nav nav-pills pull-right">
                    <li role="presentation" class="active"><a href="/">Home</a></li>
                    <li role="presentation"><a href="/login">Sign In</a></li>
                    <li role="presentation"><a href="/signUp">Sign Up</a></li>
                </ul>
            </nav>
            <img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ > 
        </div>
      <div class="jumbotron">
        <h1>{{error}}</h1>        
      </div>
        <footer class="footer">
            <p>©tutorial101.blogspot.com</p>
        </footer>
    </div>
</body>
</html>

templates/addBlog.html
//templates/addBlog.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Add Blog</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">
        <div class="header">
            <nav>
                <ul class="nav nav-pills pull-right">
                    <li role="presentation" class="active"><a href="/userHome">Dashboard</a></li>
                    <li role="presentation"><a href="/addBlog">Add Blog</a></li>
                    <li role="presentation"><a href="/logout">Log Out</a></li>
                </ul>
            </nav>
            <img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ > 
        </div>
     <section>
     <form class="form-horizontal" method="post" action="/addBlog">
<fieldset>
<legend>Create Your Blog</legend>
		{% if error %}
		  <div class="alert alert-danger">{{error}}</div>
		{% endif %}
<div class="form-group">
  <label class="col-md-4 control-label" for="txtTitle">Title</label>  
  <div class="col-md-4">
  <input id="txtTitle" name="inputTitle" type="text" placeholder="placeholder" class="form-control input-md">
  </div>
</div>
<div class="form-group">
  <label class="col-md-4 control-label" for="txtPost">Post</label>
  <div class="col-md-4">                     
    <textarea class="form-control" id="txtPost" name="inputDescription" ></textarea>
  </div>
</div>
<div class="form-group">
  <label class="col-md-4 control-label" for="singlebutton"></label>
  <div class="col-md-4">
    <input id="singlebutton" name="singlebutton" class="btn btn-primary" type="submit" value="Publish" />
  </div>
</div>
</fieldset>
</form>
</section>
        <footer class="footer">
            <p>©tutorial101.blogspot.com</p>
        </footer>
    </div>
  </body>
</html>

Thursday, October 8, 2020

Python Flask MongoDB Login Register logout with Jquery ajax and password hash

 


Python Flask MongoDB Login Register logout with Jquery ajax and password hash

create a file called app.py

CREATE TABLE `users` (

  `id` int(11) NOT NULL,

  `name` varchar(150) NOT NULL,

  `email` varchar(150) NOT NULL,

  `password` varchar(150) NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=latin1;


 
#app.py
from flask import Flask, render_template, json, request, redirect, session
from flask_mysqldb import MySQL,MySQLdb #pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb
from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)

app.secret_key = "caircocoders-ednalan-2020"

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'flaskdb'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)


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

@app.route('/userHome')
def userHome():
    print(session.get('sessionusername'))	
    if session.get('sessionusername'):
        return render_template('userHome.html')
    else:
        return render_template('error.html',error = 'Unauthorized Access')

@app.route('/logout')
def logout():
    session.pop('sessionusername', None)
    return redirect('/')
	
@app.route('/signUp',methods=['POST','GET'])
def signUp():
    if request.method == 'POST':
        _name = request.form['inputName']
        _email = request.form['inputEmail']
        _password = request.form['inputPassword']
        # validate the received values
        if _name and _email and _password:
            _hashed_password = generate_password_hash(_password)
            curl = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
            curl.execute("SELECT * FROM users WHERE email=%s",(_email,))
            user = curl.fetchone()
            #print(user)
            if user is None:		
                curl.execute("INSERT INTO users (name, email, password) VALUES (%s,%s,%s)",(_name,_email,_hashed_password,))
                mysql.connection.commit()
                curl.close()
                return json.dumps({'message':'User created successfully !'})
            else:
                return json.dumps({'html':'A user with this email address already exists'})
        else:
            msg =  '{ "html":"Enter the required fields"}'
            msghtml = json.loads(msg)
            return msghtml["html"]
    else:
        return render_template("signup.html")

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        # Get Form Fields
        _username = request.form['inputEmail']
        _password = request.form['inputPassword']
  
        cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
  
        # Get user by username
        result = cur.execute("SELECT * FROM users WHERE email = %s", [_username])
  
        if result > 0:
            # Get stored hash
            data = cur.fetchone()
            password = data['password']
  
            # Compare Passwords 
            if check_password_hash(password, _password):
                # Passed
                session['sessionusername'] = _username
                return redirect('/userHome')
            else:
                error = 'Invalid login'
                return render_template('signin.html', error=error)
            # Close connection
            cur.close()
        else:
            error = 'Username not found'
            return render_template('signin.html', error=error)
  
    return render_template('signin.html')
         
if __name__ == '__main__':
    app.run(debug=True)
Home Page
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login Register logout with Jquery ajax, json and MySQLdb and password hash</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">
        <div class="header">
            <nav>
                <ul class="nav nav-pills pull-right">
                    <li role="presentation" class="active"><a href="/">Home</a></li>
                    <li role="presentation"><a href="/login">Sign In</a></li>
                    <li role="presentation"><a href="/signUp">Sign Up</a></li>
                </ul>
            </nav>
            <img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ > 
        </div>
        <div class="jumbotron">
            <h2>Login Register logout with Jquery ajax, json and MySQLdb and password hash</h2>
            <p class="lead"></p>
            <p><a class="btn btn-lg btn-success" href="signUp" role="button">Sign Up</a>
            </p>
        </div>
        <div class="row marketing">
            <div class="col-lg-6">
                <h4>Blog 1</h4>
                <p>Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</p>
            </div>
            <hr>
            <div class="col-lg-6">
                <h4>Blog 1</h4>
                <p>Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</p>
            </div>
        </div>
        <footer class="footer">
            <p>©tutorial101.blogspot.com</p>
        </footer>
    </div>
</body>
</html>
Sign Up page
templates/signup.html
//templates/signup.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login Register logout with Jquery ajax, json and MySQLdb and password hash</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>
<script src="/static/js/signUp.js"></script>
</head>
<body>
    <div class="container">
        <div class="header">
            <nav>
                <ul class="nav nav-pills pull-right">
                    <li role="presentation" class="active"><a href="/">Home</a></li>
                    <li role="presentation"><a href="/login">Sign In</a></li>
                    <li role="presentation"><a href="/signUp">Sign Up</a></li>
                </ul>
            </nav>
            <img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ > 
        </div>
      <div class="jumbotron">
        <h2>Login Register logout with Jquery ajax, json and MySQLdb and password hash</h2>
		<div id="message"></div>
        <form class="form-signin">
        <p><label for="inputName" class="sr-only">Name</label>
        <input type="name" name="inputName" id="inputName" class="form-control" placeholder="Name" required autofocus></p>
        <p><label for="inputEmail" class="sr-only">Email address</label>
        <input type="email" name="inputEmail" id="inputEmail" class="form-control" placeholder="Email address" required autofocus></p>
        <p><label for="inputPassword" class="sr-only">Password</label>
        <input type="password" name="inputPassword" id="inputPassword" class="form-control" placeholder="Password" required></p>
        <p><button id="btnSignUp" class="btn btn-lg btn-primary btn-block" type="button">Sign up</button></p>
      </form>
      </div>
      <footer class="footer">
         <p>©tutorial101.blogspot.com</p>
      </footer>
    </div>
  </body>
</html>
Jquery Ajax static/js/signUp.js
//static/js/signUp.js
$(function() {
    $('#btnSignUp').click(function() {
        $.ajax({
            url: '/signUp',
            data: $('form').serialize(),
            type: 'POST',
            success: function(response) {
                console.log(response);
				$('#message').html(response);
            },
            error: function(error) {
                console.log(error);
				$('#message').html(error);
            }
        });
    });
});
Login Page
templates/signin.html
//templates/signin.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login Register logout with Jquery ajax, json and MySQLdb and password hash</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">
        <div class="header">
            <nav>
                <ul class="nav nav-pills pull-right">
                    <li role="presentation" class="active"><a href="/">Home</a></li>
                    <li role="presentation"><a href="/login">Sign In</a></li>
                    <li role="presentation"><a href="/signUp">Sign Up</a></li>
                </ul>
            </nav>
            <img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ > 
        </div>
      <div class="jumbotron">
        <h2>Login Register logout with Jquery ajax and json</h2>
		{% if error %}
		  <div class="alert alert-danger">{{error}}</div>
		{% endif %}
        <form class="form-signin" action="/login" method="post">
        <p><label for="inputEmail" class="sr-only">Email address</label>
        <input type="email" name="inputEmail" id="inputEmail" class="form-control" placeholder="Email address" required autofocus></p>
        <p><label for="inputPassword" class="sr-only">Password</label>
        <input type="password" name="inputPassword" id="inputPassword" class="form-control" placeholder="Password" required></p>
        
        <p><button id="btnSignIn" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button></p>
      </form>
      </div>
        <footer class="footer">
            <p>©tutorial101.blogspot.com</p>
        </footer>
    </div>
  </body>
</html>
Userhome page
templates/userHome.html
//templates/userHome.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login Register logout with Jquery ajax, json and MySQLdb and password hash</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">
        <div class="header">
            <nav>
                <ul class="nav nav-pills pull-right">
                    <li role="presentation" class="active"><a href="/userHome">Dashboard</a></li>
                    <li role="presentation"><a href="/logout">Log Out</a></li>
                </ul>
            </nav>
            <img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ > 
        </div>
      <div class="jumbotron">
        <h1>Dashboard <small> Welcome {{session.sessionusername}}</small></h1>
      </div>      
        <footer class="footer">
            <p>©tutorial101.blogspot.com</p>
        </footer>
    </div>
</body>
</html>
Error Page
templates/error.html
templates/error.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Unauthorized Access</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">
        <div class="header">
            <nav>
                <ul class="nav nav-pills pull-right">
                    <li role="presentation" class="active"><a href="/">Home</a></li>
                    <li role="presentation"><a href="/login">Sign In</a></li>
                    <li role="presentation"><a href="/signUp">Sign Up</a></li>
                </ul>
            </nav>
            <img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ > 
        </div>
      <div class="jumbotron">
        <h1>{{error}}</h1>        
      </div>
        <footer class="footer">
            <p>©tutorial101.blogspot.com</p>
        </footer>
    </div>
</body>
</html>

Monday, October 5, 2020

Python Flask AJAX WITH JQUERY and JSON | Sign Up using MySQLdb Database

 



Python Flask AJAX WITH JQUERY and JSON | Sign Up using MySQLdb Database

Database Table
CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `name` varchar(150) NOT NULL,
  `email` varchar(150) NOT NULL,
  `password` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Sing-up method in app.py
 
from flask import Flask, render_template, request, url_for, json
from flask_mysqldb import MySQL,MySQLdb #pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb
from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)

app.secret_key = "caircocoders-ednalan-2020"

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'flaskdb'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)


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

@app.route('/signUp',methods=['POST','GET'])
def signUp():
    _name = request.form['inputName']
    _email = request.form['inputEmail']
    _password = request.form['inputPassword']
    # validate the received values
    if _name and _email and _password:
            
        # All Good, let's call MySQL
        cur = mysql.connection.cursor()
        _hashed_password = generate_password_hash(_password)
        cur.execute("INSERT INTO users (name, email, password) VALUES (%s,%s,%s)",(_name,_email,_hashed_password,))
        data = cur.fetchall()

        if len(data) is 0:
            mysql.connection.commit()
            return json.dumps({'message':'User created successfully !'}) #json.dumps() takes in a json object and returns a string.
        else:
            return json.dumps({'error':str(data[0])})
    else:
        x =  '{ "html":"Enter the required fields"}'
        y = json.loads(x)	#json.loads() takes in a string and returns a json object.	
        return y["html"]
	
if __name__ == '__main__':
    app.run(debug=True)
Sign-up page - signUp.html
We may want to create a Sign Up page called templates/signUp.html using Bootstrap to power our html files:
we'll use jQuery AJAX to post the form data to the Python Flask method.
JavaScript file called signUp.js and include it after jQuery in signUp.html.

//templates/signup.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Python Flask AJAX WITH JQUERY and JSON | Sign Up using MySQLdb 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>
<script src="/static/js/signUp.js"></script>
</head>
<body>
    <div class="container">
      <div class="header">
        <nav>
          <ul class="nav nav-pills pull-right">
            <li role="presentation" ><a href="/">Home</a></li>
            <li role="presentation"><a href="/showSignin">Sign In</a></li>
            <li role="presentation" class="active"><a href="showSignUp">Sign Up</a></li>
          </ul>
        </nav>
        <img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ >
      </div>
      <div>
        <h1>Python Flask AJAX WITH JQUERY and JSON</h1>
		<div id="message"></div>
        <form class="form-signin">
        <p><label for="inputName" class="sr-only">Name</label>
        <input type="name" name="inputName" id="inputName" class="form-control" placeholder="Name" required autofocus></p>
        <p><label for="inputEmail" class="sr-only">Email address</label>
        <input type="email" name="inputEmail" id="inputEmail" class="form-control" placeholder="Email address" required autofocus></p>
        <p><label for="inputPassword" class="sr-only">Password</label>
        <input type="password" name="inputPassword" id="inputPassword" class="form-control" placeholder="Password" required></p>
        <p><button id="btnSignUp" class="btn btn-lg btn-primary btn-block" type="button">Sign up</button></p>
      </form>
      </div>
      <footer class="footer">
        <p>©youtube.com/cairocoders</p>
      </footer>
    </div>
  </body>
</html>
//static/js/signUp.js
$(function() {
    $('#btnSignUp').click(function() {
        $.ajax({
            url: '/signUp',
            data: $('form').serialize(),
            type: 'POST',
            success: function(response) {
                console.log(response);
				$('#message').html(response);
            },
            error: function(error) {
                console.log(error);
				$('#message').html(error);
            }
        });
    });
});

Sunday, August 2, 2020

Python Flask Mysqldb Simple Login Register and Logout



Python Flask Mysqldb Simple Login Register and Logout

Database Table

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `name` varchar(150) NOT NULL,
  `email` varchar(150) NOT NULL,
  `password` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `users` (`id`, `name`, `email`, `password`) VALUES
(1, 'Cairocoders', 'cairocoders@gmail.com', '$2b$12$7RXKIh40P94SdbmrKZH2V.UjbZoAMJ7tVfOQ4zc1nkGGC8ypaSyma');




app.py
 
#app.py
from flask import Flask, render_template, request, redirect, url_for, session
from flask_mysqldb import MySQL,MySQLdb #pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb
import bcrypt #pip install bcrypt https://pypi.org/project/bcrypt/

app = Flask(__name__)

app.secret_key = "caircocoders-ednalan-2020"

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'flaskdb'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)

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

@app.route('/register', methods=["GET", "POST"]) 
def register():
    if request.method == 'GET':
        return render_template("register.html")
    else:
        name = request.form['name']
        email = request.form['email']
        password = request.form['password'].encode('utf-8')
        hash_password = bcrypt.hashpw(password, bcrypt.gensalt())

        cur = mysql.connection.cursor()
        cur.execute("INSERT INTO users (name, email, password) VALUES (%s,%s,%s)",(name,email,hash_password,))
        mysql.connection.commit()
        session['name'] = request.form['name']
        session['email'] = request.form['email']
        return redirect(url_for('home'))

@app.route('/login',methods=["GET","POST"])
def login():
    if request.method == 'POST':
        email = request.form['email']
        password = request.form['password'].encode('utf-8')

        curl = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        curl.execute("SELECT * FROM users WHERE email=%s",(email,))
        user = curl.fetchone()
        curl.close()

        if len(user) > 0:
            if bcrypt.hashpw(password, user["password"].encode('utf-8')) == user["password"].encode('utf-8'):
                session['name'] = user['name']
                session['email'] = user['email']
                return render_template("home.html")
            else:
                return "Error password and email not match"
        else:
            return "Error user not found"
    else:
        return render_template("login.html")

@app.route('/logout')
def logout():
    session.clear()
    return render_template("home.html")
	
if __name__ == '__main__':
    app.run(debug=True)
templates/layout.html
//templates/layout.html
<!DOCTYPE html>
<html>
 <head>
 <meta charset="utf-8" />
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <title>{% block title %} {% endblock %}</title>
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
 </head>
 <body>
 <nav class="navbar navbar-default">
 <div class="container">
 <div class="navbar-header">
 <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
 <span class="sr-only">Toggle navigation</span>
 <span class="icon-bar"></span>
 <span class="icon-bar"></span>
 <span class="icon-bar"></span>
 </button>
 <a class="navbar-brand" href="#">Flask User Auth</a>
 </div>
 <div id="navbar" class="collapse navbar-collapse">
 <ul class="nav navbar-nav">
 <li>
 <a href="/">Home</a>
 </li>
{% if session['name'] %}
 <li>
 <a href="/logout">Logout</a>
 </li>
 {% else %}
 <li>
 <a href="/login">Login</a>
 </li>
 <li>
 <a href="/register">Register</a>
 </li>
 {% endif %}
 </ul>
 </div>
 </div>
 </nav>
{% block content %} {% endblock %}
 <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </body>
</html>
templates/home.html
//templates/home.html
{% extends 'layout.html' %}
{% block title %} Home {% endblock %}
{% block content %}
<div class="container">
 <div class="row">
 <div class="col-md-6 col-md-offset-3"><h1>
Home page
{% if session['name'] %}
Welcome {{ session['name'] }}
{% else %}
Not login
{% endif %}</h1>
 </div>
 </div>
</div>
{% endblock %}
templates/register.html
//templates/register.html
{% extends 'layout.html' %}
{% block title %} Register {% endblock %}
{% block content %}
 <div class="container">
 <div class="row">
 <div class="col-md-6 col-md-offset-3">
 <form action="/register" method="POST">
 <div class="form-group">
 <label>Name:</label>
 <input type="text" class="form-control" name="name">
 </div>
 <div class="form-group">
 <label>Email:</label>
 <input type="email" class="form-control" name="email">
 </div>
 <div class="form-group">
 <label>Password:</label>
 <input type="password" class="form-control" name="password">
 </div>
 <div class="form-group">
 <button class="btn btn-primary">Register</button>
 </div>
 </form>
 </div>
 </div>
</div>
{% endblock %}
templates/login.html
//templates/login.html
{% extends 'layout.html' %}
{% block title %} Login {% endblock %}
{% block content %}
<div class="container">
 <div class="row">
 <div class="col-md-6 col-md-offset-3">
 <form action="/login" method="POST">
 <div class="form-group">
 <label>Email:</label>
 <input type="email" class="form-control" name="email">
 </div>
 <div class="form-group">
 <label>Password:</label>
 <input type="password" class="form-control" name="password">
 </div>
 <div class="form-group">
 <button class="btn btn-primary">Login</button>
 </div>
 </form>
 </div>
 </div>
</div>
{% endblock %}

Thursday, July 23, 2020

Python Django How to Create a simple Autocomplete Dropdown using HTML5 Datalist


Python Django How to Create a simple Autocomplete Dropdown using HTML5 Datalist


views.py
 
#views.py
from django.shortcuts import render
from myapp.models import City
 
def showlist(request):
    results=City.objects.all
    return render(request, "home.html",{"showcity":results})
models.py
 
#models.py
from django.db import models
  
class City(models.Model):
    name = models.CharField(max_length=30)
   
    def __str__(self):
        return self.name
     
    class Meta:
        db_table = 'myapp_city'
templates/home.html
//templates/home.html
{% extends 'base.html' %}

{% block content %}
    <p>Enter your City:</p>
    <input type="text" list="citylist" Placeholder="Search City.." class="form-control" style="width:300px;">
    <datalist id="citylist">
 {% for results in showcity %}
        <option value="{{ results.name}}">
 {% endfor %}
    </datalist>
{% endblock %}
templates/base.html
//templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
 <title>{% block title %}Python Django How to Create a simple Autocomplete Dropdown using HTML5 Datalist{% endblock %}</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Cairocoders</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
    <div class="navbar-nav">
   <a class="nav-item nav-link active" href="">Home</a>
    </div>
  </div>
</nav>
 <div class="container" style="padding:20px;">
    <div class="col-md-12 well">
        <h3 class="text-primary">Python Django How to Create a simple Autocomplete Dropdown using HTML5 Datalist</h3> 
        <hr style="border-top:1px dotted #ccc;"/>
  {% block content %} {% endblock %}
    </div>
    </div> 
</body>
</html>

Sunday, July 19, 2020

Python Django Simple Dropdown List Binding Populate Data

Python Django Simple Dropdown List Binding Populate Data


views.py
 
#views.py
from django.shortcuts import render
from myapp.models import City

def showlist(request):
    results=City.objects.all
    return render(request, "home.html",{"showcity":results})
models.py
 
#models.py
from django.db import models
 
class City(models.Model):
    name = models.CharField(max_length=30)
  
    def __str__(self):
        return self.name
    
    class Meta:
        db_table = 'myapp_city'
urls.py
 
#urls.py
from django.contrib import admin  
from myapp import views  
from django.conf.urls import url
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('showlist/', views.showlist, name='showlist'),
]
templates/home.html
//templates/home.html
{% extends 'base.html' %}

{% block content %}
  <p><b>City : </b> 
         <select name="city" class="form-control">
   {% for results in showcity %}
            <option value="{{ results.id}}">{{ results.name}}</option>
   {% endfor %}
         </select>
</p>  
{% endblock %}
templates/base.html
//templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
 <title>{% block title %}Python Django Simple Dropdown List Binding Populate Data {% endblock %}</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Cairocoders</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
    <div class="navbar-nav">
   <a class="nav-item nav-link active" href="">Home</a>
    </div>
  </div>
</nav>
 <div class="container" style="padding:20px;">
    <div class="col-md-12 well">
        <h3 class="text-primary">Python Django Simple Dropdown List Binding Populate Data</h3> 
        <hr style="border-top:1px dotted #ccc;"/>
  {% block content %} {% endblock %}
    </div>
    </div> 
</body>
</html>

Related Post