article

Showing posts with label mongoDB. Show all posts
Showing posts with label mongoDB. Show all posts

Sunday, November 8, 2020

DataTable Inline Editing using Python Flask MongoDB CRUD (Create, Read, Update, Delete) with jquery ajax and X-Editable


DataTable Inline Editing using Python Flask MongoDB CRUD (Create, Read, Update, Delete) with jquery ajax and X-Editable

DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, built upon the foundations of progressive enhancement, that adds all of these advanced features to any HTML table.

https://datatables.net/

X-editable
This library allows you to create editable elements on your page. It can be used with any engine (bootstrap, jquery-ui, jquery only) and includes both popup and inline modes.

https://vitalets.github.io/x-editable/

ModuleNotFoundError: No module named 'flask_mongoengine'
Install
(venv) C:\flaskmyproject>pip install flask-mongoengine
app.py
 
#app.py
from flask import Flask, request, jsonify, render_template, json, redirect
from flask_mongoengine import MongoEngine #ModuleNotFoundError: No module named 'flask_mongoengine' = (venv) C:\flaskmyproject>pip install flask-mongoengine
from datetime import datetime

app = Flask(__name__)
app.config['MONGODB_SETTINGS'] = {
    'db': 'dbmongocrud',
    'host': 'localhost',
    'port': 27017
}
db = MongoEngine()
db.init_app(app)
 
class Employee(db.Document):
    name = db.StringField()
    email = db.StringField()
    phone = db.StringField()
    pub_date = db.DateTimeField(datetime.now)
	
@app.route('/')
def query_records():
    employee = Employee.objects.all()
    return render_template('useradmin.html', employee=employee)
 
@app.route('/updateemployee', methods=['POST'])
def updateemployee():
    pk = request.form['pk']
    namepost = request.form['name']
    value = request.form['value']
    employee_rs = Employee.objects(id=pk).first()
    if not employee_rs:
        return json.dumps({'error':'data not found'})
    else:
        if namepost == 'name':
            employee_rs.update(name=value)
        elif namepost == 'email':
            employee_rs.update(email=value)
        elif namepost == 'phone':
            employee_rs.update(phone=value)
    return json.dumps({'status':'OK'})
	
@app.route('/add', methods=['GET', 'POST'])
def create_record():
    txtname = request.form['txtname']
    txtemail = request.form['txtemail']
    txtphone = request.form['txtphone']
    employeesave = Employee(name=txtname, email=txtemail, phone=txtphone)
    employeesave.save()
    return redirect('/')

@app.route('/delete/', methods = ['POST','GET'])
def delete_employee(getid):
    print(getid)
    employeers = Employee.objects(id=getid).first()
    if not employeers:
        return jsonify({'error': 'data not found'})
    else:
        employeers.delete()	
    return redirect('/')
	
if __name__ == '__main__':
    app.run(debug=True)
templates/useradmin.html
//templates/useradmin.html
<html>
  <head>
    <meta name="viewport" content="width=device-width">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>DataTable Inline Editing using Python Flask MongoDB jquery ajax and X-Editable</title>
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
		<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
		<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>  
		<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
		<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
		<link href="https://cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.1/bootstrap3-editable/css/bootstrap-editable.css" rel="stylesheet">
  		<script src="https://cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.1/bootstrap3-editable/js/bootstrap-editable.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
	var dataTable = $('#sample_data').DataTable();
	$('#sample_data').editable({
		container:'body',
		selector:'td.name',
		url:'/updateemployee',
		title:'Name',
		type:'POST',
		validate:function(value){
			if($.trim(value) == '')
			{
				return 'This field is required';
			}
		}
	});

	$('#sample_data').editable({
		container:'body',
		selector:'td.email',
		url:'/updateemployee',
		title:'Email',
		type:'POST',
		validate:function(value){
			if($.trim(value) == '')
			{
				return 'This field is required';
			}
		}
	});

	$('#sample_data').editable({
		container:'body',
		selector:'td.phone',
		url:'/updateemployee',
		title:'Phone',
		type:'POST',
		validate:function(value){
			if($.trim(value) == '')
			{
				return 'This field is required';
			}
		}
	});
});	
function del(ID, title){
	if (confirm("Are you sure you want to delete '" + title + "'")){
		window.location.href = '/delete/' + ID;
	}
}
</script>
	</head>
	<body>
		<div class="container">
			<h3 align="center">DataTable Inline Editing using Python Flask MongoDB CRUD (Create, Read, Update, Delete) with jquery ajax and X-Editable</h3>
			<br />
			<div class="panel panel-default">
				<div class="panel-heading">
				<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
				  Add New Employee
				</button>
				</div>
				<div class="panel-body">
					<div class="table-responsive">
						<table id="sample_data" class="table table-bordered table-striped">
							<thead>
								<tr>
									<th>ID</th>
									<th>Name</th>
									<th>Email</th>
									<th>Phone</th>
									<th>Delete</th>
								</tr>
							</thead>
							<tbody>
								{% for row in employee %}
								<tr>
									<td data-pk="{{row.id}}">{{row.id}}</td>
									<td data-name="name" class="name" data-type="text" data-pk="{{row.id}}">{{row.name}}</td>
									<td data-name="email" class="email" data-type="text" data-pk="{{row.id}}">{{row.email}}</td>
									<td data-name="phone" class="phone" data-type="text" data-pk="{{row.id}}">{{row.phone}}</td>
									<td><a href="javascript:del('{{row.id}}','{{row.name}}')" class="btn btn-primary">Delete</a></td>
								</tr>
								{% endfor %}
							</tbody>
						</table>
					</div>
				</div>
			</div>
			
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Add New Employee</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <form role="form" method="post" action="/add">
          <div class="form-group">
            <label class="col-form-label">Name:</label>
            <input type="text" class="form-control" id="txtname" name="txtname">
          </div>
		  <div class="form-group">
            <label class="col-form-label">Email:</label>
            <input type="text" class="form-control" id="txtemail" name="txtemail">
          </div>
		  <div class="form-group">
            <label class="col-form-label">Phone:</label>
            <input type="text" class="form-control" id="txtphone" name="txtphone">
          </div>
		<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
		<input name="cmdsubmit" class="btn btn-primary" type="submit" value="Submit" />
        </form>
      </div>
    </div>
  </div>
</div>
		</div>
		<br />
		<br />
	</body>
</html>

Sunday, November 1, 2020

Flask with MongoDB how to setup and Create Read Update Delete (CRUD) methods

Flask with MongoDB how to setup and Create Read Update Delete (CRUD) methods

MongoDB is a popular database, but unlike other databases it’s classified as a NoSQL database program (MongoDB uses JSON-like documents with schema).

ModuleNotFoundError: No module named 'flask_mongoengine'

install module
(venv) C:\flaskmyproject>pip install flask-mongoengine

create file app.py
 
#app.py
import json
from flask import Flask, request, jsonify
from flask_mongoengine import MongoEngine #ModuleNotFoundError: No module named 'flask_mongoengine' = (venv) C:\flaskmyproject>pip install flask-mongoengine

app = Flask(__name__)
app.config['MONGODB_SETTINGS'] = {
    'db': 'dbtestmongo',
    'host': 'localhost',
    'port': 27017
}
db = MongoEngine()
db.init_app(app)

class User(db.Document):
    name = db.StringField()
    email = db.StringField()
    def to_json(self):
        return {"name": self.name,
                "email": self.email}

@app.route('/')
def query_records():
    name = 'tutorial101'
    user = User.objects(name=name).first()
    if not user:
        return jsonify({'error': 'data not found'})
    else:
        return jsonify(user.to_json())

@app.route('/add')
def create_record():
    user = User(name='Caite',
                email='caite@gmail.com')
    user.save()
    return jsonify(user.to_json())

@app.route('/update')
def update_record():
    name = 'tutorial101'
    user = User.objects(name=name).first()
    if not user:
        return jsonify({'error': 'data not found'})
    else:
        user.update(email='emailupdate@gmail.com')
    return jsonify(user.to_json())
	
@app.route('/delete')
def delete_record():
    name = 'tutorial101'
    user = User.objects(name=name).first()
    if not user:
        return jsonify({'error': 'data not found'})
    else:
        user.delete()
    return jsonify(user.to_json())
	
if __name__ == "__main__":
    app.run(debug=True)

Sunday, October 25, 2020

Download and install mongoDB and connect to python flask using PyMongo module

Download and install mongoDB and connect to python flask using PyMongo module

Download and install mongoDB on Windows 10 and connect to python flask using PyMongo module Source Code : In this video I am going to show How to install MongoDB on Windows 10 operating system. How to Install MongoDB Community Edition on Windows. How to Install MongoDB Compass tools How to Install python PyMongo module How to connect MongoDB to python flask pymongo and check the result MongoDB is one of the most used, open-source document database, and NoSQL database. show dbs-Print a list of all databases on the server. use {db} - Switch current database to {db} show collections-Print a list of all collections for current database. db.collection.find()-Find all documents in the collection and returns a cursor. Create database use dbtestmongo insert data db.user.insert({ "username":"tutorial101" }) show dbs show collections; db.user.find() set invironment C:\Program Files\MongoDB\Server\4.4\bin


(venv)$ pip install Flask-PyMongo
 
#app.py
from flask import Flask, jsonify
from flask_pymongo import PyMongo #(venv)$ pip install Flask-PyMongo

app = Flask(__name__)

app.config["MONGO_URI"] = "mongodb://localhost:27017/dbtestmongo"
mongo = PyMongo(app)

@app.route("/")
def index():
    online_users = mongo.db.user.find({"username": "testusername"})
    output = []
    for s in online_users:
      output.append({'User Name' : s['username']})
    return jsonify({'result' : output})
		
if __name__ == "__main__":
    app.run(debug=True)

Related Post