user2997582
user2997582

Reputation: 67

Passing data from from django view to javascript

I'm trying to create a network using the vis.js library (http://visjs.org/) and django (the basic one - http://visjs.org/examples/network/basicUsage.html). I need to pass data specifying the nodes of the network from django to javascript. This is my views.py:

def create_network(request):
    r=[]
    for i in range(1,6):
        d={}
        d['id'] = i
        d['label'] = 'Node ' + str(i)
        r.append(d)
    data = json.dumps(r)
    return render(request, 'network.html', {"nodes":data})

This is the relevant part of my template:

  n = {{ nodes }}
  var nodes = new vis.DataSet(n);

When I run this, the {{nodes}} disappears and it simply becomes:

  n = 
  var nodes = new vis.DataSet(n);

and I get unexpected token errors. I'm relatively new to Django and javascript so sorry if this seems elemenatary. How would I fix this? Thanks.

Upvotes: 2

Views: 1860

Answers (1)

acmisiti
acmisiti

Reputation: 513

Try the following:

 var n = `{{ nodes|safe }}`;
 var nodes = new vis.DataSet(n);

You may or may not need to add a jQuery.parseJSON() around the data before passing it into the vis.DataSet. I cannot say for sure because I have never used http://visjs.org/.

Upvotes: 1

Related Questions