Using Datatables with MongoDB and Python

Using Datatables with MongoDB and Python

noobdanoobda Posts: 2Questions: 1Answers: 0
edited July 2022 in Free community support

I need to use datatables for displaying the data which is in my MongoDB database on a webpage built using flask.
I'm using pymongo for connecting flask and MongoDB
My flask app has this method for the datatable part -

@app.route("/ajaxfile",methods=["POST","GET"])
def ajaxfile():
if request.method == 'POST':
draw = request.values.get('draw' )
row = request.values.get('start')
rowperpage = request.values.get('length')
searchValue = request.values.get("search[value]")

        totalRecords = collection.count_documents({})

        totalRecordwithFilter = 1

        table=collection.find().batch_size(5)
        data = []
        for row in table:

            data.append({
                'index':row["index"],
                'name': row['name'],
                'date': row['date'],

                'status': row['status']                  
            })
        response = {
            'draw': draw,
            'iTotalRecords': totalRecords,
            'iTotalDisplayRecords': totalRecordwithFilter,
            'aaData': data,
        }

        return jsonify(response)

//////////////////////////////////////////////
This is my table HTML file -

<!doctype html>
<html>

<head>
<title>Dashboard</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<link href='https://cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css' rel='stylesheet' type='text/css'>


</head>

$(document).ready(function () {


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

      { data: 'status' },

    ]
  });

});

</script>
</body>

</html>
I'm able to get a datatble but its showing all the data in the database and I'm unable to implement pagination
Need help with the pagination part

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,365Questions: 26Answers: 4,956
    Answer ✓

    Server Side Processing is a client server model. See the SSP protocol docs for details. You will need to implement the server portion of the protocol to provide searching, sorting and paging. Or use a third party Flask library like this.

    Kevin

  • noobdanoobda Posts: 2Questions: 1Answers: 0

    Thanks for the reply Kevin, the pagination is working now
    Keep up the good work

Sign In or Register to comment.