Chartjs-Getting chart.js to work with Django and Apache

1👍

If customcharts.js is within the static/yourapp you need to load your script as follows:

<script src="{% static 'yourapp/customcharts.js' %}"></script>

Don’t forget to call {% load staticfiles %}

Then, a static resource can’t call a view, you need to get the json data in the view and then pass it to the javascript function.

Your template should look as follows:

{% load staticfiles %}
<!DOCTYPE html>
<html lang='en'> 
    <meta http-equiv="content-type" content="text/html; charset=UTF8">
    <head> 
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.min.js"></script> 
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
        <script language="JavaScript" src="{% static 'yourapp/customcharts.js' %}"> </script>
        <script language="JavaScript">
            $.getJSON("{% url 'index' %}", function(data) {  // 'index' is the name of the view in your urls.py
                renderChart(data);
            });
        </script>
    </head> 
    <body> 
        <canvas id="myChart"></canvas>  
    </body> 
</html>

Hope this helps.

1👍

Use ‘polls’ instead of ‘index’

Leave a comment