Search code examples
jsondjangopandasdataframebootstrap-table

Load pandas dataframe in bootstrap table (python -> jquery) through django


I am not sure what is wrong here - I have tried all combinations but can't get it to work ... I have the following.

1/ A view created in Python with a data context variable (django framework)

def index(request):
    # Sim df
    df = pd.DataFrame()
    df = df.append({'col1': 'col1', 'col2': 'col2'}, ignore_index=True)

    # Context
    context = {
        'data': df.to_json(orient='records'),
    }
    return render(request, 'index.html', context)

2/ A loader for my dataframe table using "bootstrap-table" (part of index.html)

$(function() {
  $('#datatable').bootstrapTable({
    columns: [{
    field: 'col1',
    title: 'col1'
  }, {
    field: 'col2',
    title: 'col2'
  }],
  data: [{col1: '1', col2: 'Item1'}]
  });
});

3/ Above works just fine with two columns displayed and one row. However, if I replace and use the following it just does not anymore. No specific error but it does not display anything ...

$(function() {
  $('#datatable').bootstrapTable({
    columns: [{
    field: 'col1',
    title: 'col1'
  }, {
    field: 'col2',
    title: 'col2'
  }],
  data: '{{data}}', // loading from context
  });
});

Solution

  • In case that helps someone you had to replace by the following.

    data: {{data|safe}},
    

    And make sure the JS is within the index.html, not in a loaded external script file. That were my two mistakes...