0

In the js file below

'use strict';
$(document).ready(function() {
    buildchart()
    $(window).on('resize', function() {
        buildchart();
    });
    $('#mobile-collapse').on('click', function() {
        setTimeout(function() {
            buildchart();
        }, 700);
    });
});
function buildchart() {
    $(function() {
        var graph = Morris.Donut({
            element: 'chart-pie-moris',
            data: [{
                    value: 60,
                    label: 'Order'
                },
                {
                    value: 20,
                    label: 'Stock'
                },
                {
                    value: 10,
                    label: 'Profit'
                },
                {
                    value: 5,
                    label: 'Sale'
                }
            ],
            ......

I want to be updating the values in buildchart() function the values returned by my views file functions. Example

def order(request):
    a = 'calculated integer value'
    return a

So I would like to pass in order function to replace 60 in buildchart() function. how can I achieve this? Please help a newbie

Sammy
  • 311
  • 2
  • 9

1 Answers1

1

To use a Django variable inside JavaScript

Just, surround the Django variable by " " or ' '. Like:

<script type="text/javascript"> 
   var a = "{{someDjangoVariable}}";
   var b = "{% url 'someDjangoUrl' %}";
</script>

If you want use access in a external js file Define the variable in the html file inside a <script> block. And access to it in the external .js file like a normal js global variable :

<script type="text/javascript"> 
   var a = "{{someDjangoVariable}}";
</script>
<script type="text/javascript" href="{% static 
'path/to/your_js_file.js' %}">
// In this file you can have access to the 'a' variable.
</script>
Rvector
  • 2,312
  • 1
  • 8
  • 17