Carbon Carbon - 1 year ago 149
jQuery Question

Django passing JSON data to static getJSON/Javascript

I am trying to grab data from my and serialize it into a JSON object within my

class Platform(models.Model):
platformtype = models.CharField(max_length=25)

def startpage(request):
return render_to_response('Main.html');

def index(request):
platforms_as_json = serializers.serialize('json', Platform.objects.all())
return HttpResponse(platforms_as_json, content_type='json')

After doing this I want to pass this object into my static javascript file which is using getJSON to populate my drop down list for my template(Main.html).


$.getJSON("{{platforms_as_json}}", function (data) {
$.each(data, function (index, item) {

I have looked at many other threads within SO, but all of them are for those using embedded JS within their template and/or not using getJSON. As of right now, data is not being displayed in the list when I run my Django development server. What am I doing wrong? Thank you.


<!DOCTYPE html>


{% load static from staticfiles %}
<script type = 'text/javascript' >

var platformsjson = "({% autoescape off %}{{platforms_as_json}}{% endautoescape %})";

<select id = "platformList"></select>

<ul id = "root"></ul>
<div id = "root"></div>
<script src = "{% static 'admin/js/platformddown_script.js' %}"></script>


$.each(platformsjson, function (index, item) {

After this update it still doesn't work.

Answer Source

Main html render + json data

import json
from django.shortcuts import render

def startpage(request):
    platforms = Platform.objects.select_related().values('platformtype')
    return render(request, 'Main.html', {'platforms_as_json': json.dumps(list(platforms)),})

in template

{{ platforms_as_json }}

html and js

<select id="platformList"></select>

    $.each({% autoescape off %}{{platforms_as_json}}{% endautoescape %}, function (index, item) {

Old example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download