Carbon Carbon - 4 months ago 28
jQuery Question

Django passing JSON data to static getJSON/Javascript

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

Models.py:

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


Views.py:

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).

JavaScript:

$.getJSON("{{platforms_as_json}}", function (data) {
$.each(data, function (index, item) {
$('#platformList').append(
$('<option></option>').val(item).html(item.platformtype)
);
});
});


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.

UPDATE:

<!DOCTYPE html>
<html>

<head>

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

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

</script>
</head>
<body>
<select id = "platformList"></select>

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


platformddown_script.js:

$.each(platformsjson, function (index, item) {
$('#platformList').append(
$('<option></option>').val(item.platformtype).html(item.platformtype)
)
});


After this update it still doesn't work.

Answer

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>

<script>
    $.each({% autoescape off %}{{platforms_as_json}}{% endautoescape %}, function (index, item) {
        $('#platformList').append(
                $('<option></option>').val(item.platformtype).html(item.platformtype)
        )
    });
</script>

Old example https://gist.github.com/leotop/014a38bd97407a6380f2526f11d17977

Comments