I am trying to send a JSON object from a Django PostgreSQL database to a Django template. Here is my models.py
# models.py
from __future__ import unicode_literals
from django.contrib.postgres.fields import JSONField
from django.db import models
class Net(models.Model):
net_name = models.CharField(max_length=200)
def net_default():
return {"net_name": "None", "graph_data": "None", "city_data": "None"}
data = JSONField(default=net_default())
def __unicode__(self):
return self.net_name
Here is my views.py
# standard includes
from django.shortcuts import render
# my includes
from django.http import HttpResponse
from django.template import loader
# get nets
from .models import Net
def index(request):
net_q_set = Net.objects.order_by('net_name')
context = {
'nets': net_q_set,
}
return render(request, 'viewer/index.html', context)
So I have a sidebar in which the user selects a network from the 'nets' JSON object. Then a javascript function which takes the selected network name should iterate through the JSON object to get the network's nodes and get each node's latitude and longitude. I am able to iterate through the names with the following code (this code works and produces what I want):
{% for name in nets %}
<li><a href="javascript:plotMap('{{name}}');">{{name}}</a></li>
{% endfor %}
But I am having an issue establishing the JSON object in the javascript script. I have tried:
<script>
var nets = JSON.parse({{ nets }})
function plotMap(name){ ... };
</script>
But I get an error of 'unexpected token &' on the var nets line. I am guessing this is from parsing the JSON object. Is there a better way to do this? Or am I making an error I am blind to?
Edit -- 2 Using @Arpit's solution, I call
{% for name in nets %}
<li><a href='javascript:plotMap({{name.data}});'>{{name}}</a></li>
{% endfor %}
Then in the plotMap(net_json) function I immediately call alert(net_json.city_data.Perth1.lat); from my understanding this should make an alert that displays "-31.93333", instead I get an error "Uncaught SyntaxError: Unexpected string". Clicking the debugger link on that shows me:
plotMap({u'city_data': {u'Alice,Springs': {u'lat': -23.7, u'long': 133.88333}, ...}, u'graph_data': {u'nodes': [u'Perth1', ...], u'links': [[u'Perth1', u'Adelaide1'], ...]'});