article

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#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/<string:getid>', 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)
</string:getid>
templates/useradmin.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
//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>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
        <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
<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>

Related Post