Search code examples
pythonjsondjangoamcharts

pass data from Django to amchart JS with JSON


I want to pass data from my Django view to my html and then take the data to my chart js or pass the data directly to my amchart.

views.py:

def nodo_detail(request,nodo_id):
El_Nodo = Nodo.objects.get(pk=nodo_id)
all_nodos = Nodo.objects.order_by('pk').all()
var = Variable()
v = dir(var)
elemento = El_Nodo.variable_set.order_by('pk').all()
watts = elemento.last().Watts
prefix = ''
chartData = "["

for t in elemento:
    chartData += prefix
    chartData += "{\n"
    chartData += "                      date: "
    chartData += '"' + str(t.Data_time.year) + "-"
    chartData += str(t.Data_time.month) + "-"
    chartData += str(t.Data_time.day) + " "
    chartData += str(t.Data_time.hour) + ":"
    chartData += str(t.Data_time.minute) + ":"
    chartData += str(t.Data_time.second) + '"' + ",\n"
    chartData += "                  value:"
    chartData += str(t.Watts) + ",\n"
    chartData += "                  volume: "
    chartData += str(t.Watts) + "\n                      }"
    prefix = ", "
chartData += "]"

context = {'El_Nodo': El_Nodo,
           'all_nodos': all_nodos,
           'v': v,
           'watts': watts,
           'chartData':chartData,
           "asdf":json.dumps(chartData)}
return render(request, 'inicio/detail.html', context)

The data that I want to pass is chartData, with the for loop I try to do the JSON format also I try the JSON python librery.

detail.html:

{% block Stock %}
<input type="hidden"  id="stock" value="{{chartData}}"> <!-- or asdf-->
{% endblock%}

amchartjs:

var chartData = JSON.parse(document.getElementById("stock").value);
 // or directly 
var chartData = JSON.parse('{{ chartData }}');//or asdf

I understand that with this way it is necessary refresh the whole web page to view new data, Also like to know how to do it dynamic? Thanks and sorry for bad english


Solution

  • Make an AJAX call that returns an array, and you populate this in JavaScript. This implies to make a JSON view that returns a JSON array. Like this:

    class QueryResultsView(generic.TemplateView):
    
        template_name='your_template.html'
    
        def get_context_data(self, **kwargs):
            # Call the base implementation first to get a context
            context = super(QueryResultsView, self).get_context_data(**kwargs)
            # Create a variable you fill
            context['my_big_sql'] = MyModel.objects.filter(blabla=blibli)
            return context
    

    And from there, in your template file (this is your template file, not a JavaScript file) general_study_results.html add something like:

    <script>
    var myData = 
    {% for row in my_big_sql %} 
        {{ row.column }}{% if not forloop.last %},{% endif %}
    {% endfor %};
    </script>
    

    And then you have all your data in your HTML file ready to be used via amchartjs or any library you want.