0

My question is similar to the these previous questions, however I can't seem to make my code work:

How can I pass my context variables to a javascript file in Django?

How to use the context variables passed from Django in javascript?

I have a list of lists, containing data of the form:

data = [[1, 2, 3, 4, ...] [210, 346, 331, 402, ...] [...] ...] 

where the first list represents the number of each taken sample. I'm passing this data to my HTML file using a class that looks like:

class IndexView_charts(generic.TemplateView):
    """
    IndexView:
    """
    module = 'IndexView'
    template_name = charts_temp_name #variable for the template

data = ##extra code here to fetch data

def get_queryset(self):
    log(self.module, 'get_queryset', file=__file__)
    return self.data

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['data'] = self.data
    return context

And in the template, I can access the variable data as follows for example and it shows up on the webpage:

<h1> {{data.0}} </h1>

now, I'd like to access it in my script. In the same file I have the following code:

var chartData = {{ data }};
... some more code here ...
data:chartData[1] 

but I don't get the charts that I would like. If i change the occurrences of chartData[x] into lists containing some dummy data, the script works. So the problem lies at accessing the data.

AzyCrw4282
  • 7,222
  • 5
  • 19
  • 35
TomatoFarmer
  • 463
  • 3
  • 13

1 Answers1

0

It seems like the context array is not being parsed correctly to js as an array. If my commented suggestion doesn't work then you can try to use tojson template-tag to convert python list to js array.

For example,

var mylist = {{mylist|tojson}};
for(i = 0; i < mylist.length; i++){
    console.log(mylist[i])
};
AzyCrw4282
  • 7,222
  • 5
  • 19
  • 35