Search code examples
pythonstringflaskindices

Python Flask TypeError: string indices must be integers


Using Python Flask I want to take data from an Excel file and pass the content of each column to the html and use it to create a graph using chart.js, but the error I am facing is string indices must be integers.

@app.route('/data',methods = ['GET','POST'])
def data():
    if request.method == 'POST':
        file = request.form['upload-file']enter code here
        data=pd.read_excel(file)
        labels=list(file['student'])
        values=list(file['result'])

        return render_template('graph.html',labels=labels ,values=values)

Here is the part of HTML file where I am sending data

<script>
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: {{labels | safe }},
        datasets: [{
            label: '# of Votes',
            data: {{ values | safe }}, 

This is how my Excel file looks like:

student result
  0.2     14
  0.3     15
  0.4     16
  0.5     19

Full Traceback of Error


Solution

  • The error is caused by trying to slice a file object with []. This is not possible. You are probably trying to acces the pandas dataframe. You unfortunately forgot to add the correct variabel. So I would change

    file['student']
    

    To:

    data['student']