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.

2
  • Have your tried using escapejs built in tag, e.g. '{{ python_object|escapejs }}';? Commented Jul 28, 2020 at 18:52
  • Is the problem solved? Commented Jul 30, 2020 at 17:45

1 Answer 1

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])
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.