Edgar Navasardyan Edgar Navasardyan - 5 months ago 8
Javascript Question

Rendering tables in Django templates using JSON

I am currently working on the architecture of my Django app.
Ultimately, my goal is to parse JSON object which I pass from the Django view to the template:

The view:

tasks_queryset = TaskResponsiblePeople.objects.select_related('task')
tasks_json = serializers.serialize("json", tasks_queryset)
return render_to_response('task_management/task_list.html',

The template:

<table stupid-attribute = {{tasks_json}}>

Now, my questions is, is there any way to pass the parameter to Javascript so that some function renders the table on page load event without using "stupid-attribute"? I came across a topic which is very related to my question with only exception that I can't figure out what is meant by

JavaScript portion of the template

Specifically, could anyone make it clear, where exactly in my code I should use the analogue of

{% if tags %}
var tagbs = {{ tags|safe }};
var tgs = JSON.parse(tagbs);
{% endif %}

from the previous discussion, and could I rewrite the code below using python syntax without having to generate "dirty" HTML like this:

for (var i = 0; i < data.length; i++)
tr = $('<tr style = "cursor:pointer"/>');
tr.append('<td><input class = "tableRowChecker" type="checkbox"></td>');

if (data[i].fields.status == 1)
tr.append("<td>" +
" <div onclick = 'change_task_status(" + data[i].pk + ')' " +
" class='glyphicon glyphicon-ok'></div></td>");
tr.append("<td>" +
"<div onclick = 'change_task_status(" + data[i].pk + " , false)' " +
" style = 'color:rgb(102,204,255)' class='glyphicon glyphicon-ok'></div></td>");
$('#task_table tbody').append(tr);


I don't know what's wrong with what you have, if you replace stupid-attribute with the actually-supported attribute data, but if you did want to include it elsewhere you would just need to add a bit of actual Javascript.

<script type='text/javascript'>
    ... JSON code here ...