1

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',
                          {'task_form':task_form,
                           'responsible_people_form':responsible_people_form,
                           'tasks_json':tasks_json},
                           context_instance=RequestContext(request))

The template:

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

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);
  alert("done");
{% 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>");         
            else
                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);
        }
Community
  • 1
  • 1
Edgar Navasardyan
  • 4,261
  • 8
  • 58
  • 121

2 Answers2

2

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 ...
</script>
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Well, the key point here is that I would like the script to be in an external file. As I understand, if I write the script in the template file, than I will be able to use the context variable from Django straight away. But what about external scripts – Edgar Navasardyan May 17 '16 at 12:38
  • I'm not sure what you're saying. You can put your JSON in a script snippet in the template, and the rest of your script in an external JS file, if that's what you want. – Daniel Roseman May 17 '16 at 12:42
  • But it appears that I can't use python syntax in JS (like, say, {% if tags %}). I can only use it in HTML. Then how does the guy use alert ? – Edgar Navasardyan May 17 '16 at 12:56
  • 1
    Once again, I have no idea what you mean. You can put Django syntax anywhere in a Django template. – Daniel Roseman May 17 '16 at 13:15
  • Ok, Daniel, I already got it. Thank you much for bearing with me – Edgar Navasardyan May 17 '16 at 13:16
  • Daniel, please, bear with me. I ticked the question as answered because I did not make the question clear enough previously. I've edited the question to include the js code where I build my table's html part in a cycle. I call it "dirty" HTML because as you see, the code is not as readable as it would be with python-like syntax. Is there any way to avoid using this style ? – Edgar Navasardyan May 17 '16 at 16:51
  • I'm sorry, again I don't really follow you. What does this have to do with the question you were asking about outputting JSON? And if you just want to output a table, why are you using JSON/JS at all; why not just do it with the Django template tags? – Daniel Roseman May 17 '16 at 17:31
  • Daniel, there's only one reason for using JSON - python dictionary does not allow for arithmetic operations. Say, I can't write something like {{dict.field1}}{{dict.field2}}{{dict.field1 + dict.field2}}. You could say I can do this on server side, but my calculations can go far beyond simple sum and I don't like the idea of using server resourses for this. – Edgar Navasardyan May 18 '16 at 07:56
1

Alternative approach, is there any need for javascript? If I'm reading this right, you have some sort of structured data and want to put it into a table, which may require some reshaping of the JSON object, but otherwise is totally possible. Something like this:

pass some sort of json object that looks like:

[
  {
    "task name": "first thing",
    "id": 1,
    "date": "01/01/2010"
  },
  {
    "task name": "second thing",
    "id": 2,
    "date": "02/02/2010"
  },
  {
    "task name": "third thing",
    "id": 3,
    "date": "03/03/2010"
  },
  {
    "task name": "fourth thing",
    "id": 4,
    "date": "04/04/2010"
  }
]

then in the template, something like this:

<thead>
    <tr>
        <th>Task</th>
        <th>ID</th>
        <th>Date</th>
    </tr>
</thead>
<tbody>
{% for task in task_json %}
    <tr>
        <td>{{task.name}}</td>
        <td>{{task.id}}</td>
        <td>{{task.date}}</td>
    </tr>
{% endfor %}
</tbody>

Could be missing something but this feels like it's getting way more complicated than it needs to be.

cbrainerd
  • 426
  • 5
  • 7
  • I tried your solution, and my json looks exactly like this one (http://stackoverflow.com/questions/9592290/how-to-iterate-json-dictionary-in-django-template). The strange thing is that my loop works very slowly and renders hundres of rows instead of only 20. – Edgar Navasardyan May 18 '16 at 07:53
  • Can you post what the JSON object looks like? The exact syntax in the template would be dependent on the formatting of the JSON – cbrainerd May 18 '16 at 11:12