0

I don't know, where is my fault. DataTables is not showing any data. Is there an error with the code I have made? The flow is that I upload a csv file and after clicking the submit button it will redirect to the url /training which will display data with DataTables

Here is my flask code:

from flask import Flask, render_template, request, session, send_from_directory
from werkzeug.utils import secure_filename
from utils_process import text_preprocessing

app = Flask(__name__)

@app.route('/training', methods=['GET','POST'])
def training():
global data
if request.method == 'POST':
    uploaded_df = request.files['file']
    data_filename = secure_filename(uploaded_df.filename)
    uploaded_df.save(os.path.join(app.config['UPLOAD_FOLDER'], data_filename))
    session['uploaded_data_file_path'] = os.path.join(app.config['UPLOAD_FOLDER'], data_filename)
    filepath = session['uploaded_data_file_path']

    dict_data = []
    with open(filepath, encoding="utf8") as file:
        csv_file = csv.DictReader(file)
        for row in csv_file:
            dict_data.append(row)

    data = []
    for row in dict_data:
        row['text_clean'] = text_preprocessing(row['content'])    
        
        data.append({
            'content': row['content'],
            'text_clean': row['text_clean'],
            'rating': row['rating'],
            'sistem': row['sistem'],
            'layanan': row['layanan'],
            'transaksi': row['transaksi'],
            'pendaftaran_subsidi': row['pendaftaran subsidi'],
            'kebermanfaatan': row['kebermanfaatan']
        })
    print(data)
return render_template('training.html', data=json.dumps(data))

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

Here is my template code :

{% extends "layout.html" %}
{% block content %}
<div class="container">
   <div class="p-5 bg-white rounded shadow mb-5">
    <table id='trainingTable' class='display dataTable' width='100%'>
        <thead>
        <tr>
            <th>Content</th>
            <th>Text Clean</th>
            <th>Rating</th>
            <th>Sistem</th>
            <th>Layanan</th>
            <th>Transaksi</th>
            <th>Pendaftaran Subsidi</th>
            <th>Kebermanfaatan</th>
        </tr>
        </thead>
    </table>
  </div>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
<script>
  $(document).ready(function() {
    $('#trainingTable').DataTable({
        'ajax': {
            'url':'/training',
            'dataType': 'json',
        },
        searching: true,
        sort: true,
        scrollY: 200,
        scrollX: true,
        'columns': [
            { data: 'content' },
            { data: 'text_clean' },
            { data: 'rating' },
            { data: 'sistem' },
            { data: 'layanan' },
            { data: 'transaksi' },
            { data: 'pendaftaran_subsidi' },
            { data: 'kebermanfaatan' },
        ]
    });
});
 
</script>

{% endblock %}

Here is the result DataTables enter image description here

The data appears in the cmd terminal when I print(data) enter image description here

1
  • We can't see the structure of your JSON (the start of the JSON is not shown in your screenshot) but try adding dataSrc: '' to the 'ajax': { ... } section of your DataTable definition. If this works, that is because the JSON is an unnamed array - so you can refer to that using an empty string ''. See dataSrc. If that does not work, show us the structure of your JSON (how it starts). Commented Mar 21, 2023 at 17:52

1 Answer 1

0

You should decide whether to get your data via Ajax from a separate endpoint or pass it directly to the template.

With the former, the data is sent separately from the template as JSON. As mentioned, you need a separate endpoint for this and I recommend using jsonify. Then you can use the ajax attribute of datatables as done in your code to get the data from said endpoint.

The example below uses the alternative without saving the uploaded file. The data is passed to the template. Then the jinja filter tojson is used to convert the data so that it can then be used within datatables.

import csv, io

# ...

@app.route('/training', methods=['GET', 'POST'])
def training():
    data = []
    if request.method == 'POST':
        file = request.files.get('file')
        if file: 
            with io.TextIOWrapper(file) as fh:
                reader = csv.DictReader(fh)
                for row in reader:
                    row = { k.replace(' ', '_'): v for k,v in row.items() }
                    row['text_clean'] = text_preprocessing(row['content'])
                    data.append(row)
    return render_template('training.html', **locals())
{% extends "layout.html" %}
{% block content %}
    <form method="post" enctype="multipart/form-data">
        <input type="file" name="file" />
        <button>Upload</button>
    </form>

    <hr />

    <table id='trainingTable' class='display dataTable' width='100%'>
        <thead>
            <tr>
                <th>Content</th>
                <th>Text Clean</th>
                <th>Rating</th>
                <th>Sistem</th>
                <th>Layanan</th>
                <th>Transaksi</th>
                <th>Pendaftaran Subsidi</th>
                <th>Kebermanfaatan</th>
            </tr>
        </thead>
    </table>

    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script>
        $(function() {
            $('#trainingTable').DataTable({
                searching: true,
                sort: true,
                scrollY: 200,
                scrollX: true,
                data: {{ data|tojson }}, 
                columns: [
                    { data: 'content' },
                    { data: 'text_clean' },
                    { data: 'rating' },
                    { data: 'sistem' },
                    { data: 'layanan' },
                    { data: 'transaksi' },
                    { data: 'pendaftaran_subsidi' },
                    { data: 'kebermanfaatan' },
                ]
            });
        });
    </script>
{% endblock %}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.