I'm using Django to create a web-based app for a project, and I'm running into issues returning an array from a Django view to a template.
The array will be used by a JavaScript (JQuery) script for drawing boxes on an image shown in the page. Therefore, this array will have, among other things, coordinates for the boxes to be drawn.
This is the code in the Django view used to get the required data and serialize it as JSON:
def annotate(request, ...):
...
oldAnnotations = lastFrame.videoannotation_set.filter(ParentVideoLabel=label)
tags = serializers.serialize("json", oldAnnotations)
...
return render_to_response('vannotate.html', {'tags': tags, ...})
As a way of debugging, using {{ tags }}
in the HTML portion of the template gives this as output (sorry for the long line):
[{"pk": 491, "model": "va.videoannotation", "fields": {"ParentVideoFile": 4, "ParentVideoFrame": 201, "ParentVideoLabel": 4, "top": 220, "height": 30, "width": 30, "ParentVideoSequence": 16, "left": 242}}, {"pk": 492, "model": "va.videoannotation", "fields": {"ParentVideoFile": 4, "ParentVideoFrame": 201, "ParentVideoLabel": 4, "top": 218, "height": 30, "width": 30, "ParentVideoSequence": 16, "left": 307}}]
which I assume is the correct format for a JSON array.
Later on in the template, I attempt to actually use the tags
variable in the JavaScript portion of the template, as follows:
{% if tags %}
var tagbs = {{ tags|safe }};
var tgs = JSON.parse(tagbs);
alert("done");
{% endif %}
If I remove the var tgs = JSON.parse(tagbs);
line, then the alert box pops up fine, and the rest of the JavaScript works as expected. Leaving this line in breaks the script, however.
I want to be able to iterate through all the objects in the Django model and get values of fields in JavaScript.
I'm not sure what I'm doing wrong here, could someone point out the right way to do this?
See Question&Answers more detail:
os