how to display plotly json object in html template

Viewed 269

I have a django application that displays a few charts generated using plotly.

This is my views.py file

def home(request):
    const_list = pd.read_csv('./const.csv').Const.unique()
    party_list = pd.read_csv('./part_list.csv').abbr.unique()
    all_list = pd.read_csv('./all_list.csv').All.unique()

    chked=request.POST.get('chk', '')
    print(chked)

    if chked == 'true':
        part_bargraph = main_graph(all_list, len(const_list))
    else:
        part_bargraph = main_graph(part_list, len(const_list))

    context = {'main_graph': part_bargraph, 'const': const_list}
    print(context)
    
    return render(request, 'home.html', context)

The main_graph is a function that takes a list and an int value as parameters and generates a plotly graph. This graph is then returned as a json object using the plotly.io.to_json method.

I want to display this graph in an HTML template. This is what I am doing right now

<form method='post'>
    {% csrf_token %}
    <div class="switch">
        <input id='chk' type="checkbox" class="switch-input" />
        <label for="chk" class="switch-label">Switch</label>
    </div>
</form>

<div class="main_graph" id='main_graph'></div>

<script>
    Plotly.newPlot("main_graph", {{ main_graph | safe }})


    $(document).on('click', '#chk', function (e) {
        $.ajax({
            type: 'POST',
            url: '/home',
            data: {
                chk: $('#chk').prop('checked'),
                csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
            },
            success: function (data) {
                Plotly.newPlot("main_graph", {{ main_graph | safe }})
            }
        });
    })
</script>

When I print the context after toggling the button, I can see that the graph has changed. But I am not able to display that in the template.

What am I doing wrong?

Thanks in advance

0 Answers
Related