Hi I would like to create table using JS datatables library.
I got problem when passing value in template to js script. I created JSON object from my table which I want to display. It's passed correctly to template, when I display it everything is fine, but when trying to pass it to script nothing happend and I got empty table.
Thats the way I do it:
class VotesList(generic.ListView):
model = Vote
template_name = 'votes-list.html'
def get_context_data(self, **kwargs):
votes = Vote.objects.all().values('user', 'group', 'council')
votes_json = json.dumps(list(votes))
context = super(VotesList, self).get_context_data(**kwargs)
context['orderby'] = self.request.GET.get('orderby', 'created_date')
context['json_data'] = votes_json
return context
template:
{% block javascript %}
{% load static %}
<script type="text/javascript">
$(document).ready(function() {
var json=JSON.parse('{{ json_data | safe }}');
$('#votes_list').DataTable({
data: json,
columns:[
{ title: "user" },
{ title: "group" },
{ title: "council" }]
} );
};
</script>
{% endblock %}
{% block content %}
<p>{{ json_data | safe }}</p> <<< here data is printed fine
{% if vote_list %}
<table id="votes_list" class="display", style="width:100%">
<thead>
<tr>
<th>Właściciel</th>
<th>Grupa</th>
<th>Rada</th>
</tr>
</thead>
</table>
{% else %}
<p>Brak głosowań!</p>
{% endif %}
{% endblock %}
and output data looks like that:
[{"user": 2, "group": 1, "council": 1}, {"user": 2, "group": 2, "council": 1}, {"user": 3, "group": 1, "council": 1}, {"user": 2, "group": 1, "council": 1}, {"user": 2, "group": 2, "council": 2}, {"user": 1, "group": 1, "council": 2}, {"user": 3, "group": 1, "council": 1}, {"user": 2, "group": 1, "council": 1}, {"user": 1, "group": 1, "council": 2}, {"user": 1, "group": 2, "council": 1}, {"user": 1, "group": 1, "council": 1}, {"user": 1, "group": 1, "council": 1}]
My second question is about something else: I'm storing lot of information as choices:
STATUS_INACTIVE = 0
STATUS_ACTIVE = 1
STATUS_FINISHED = 2
STATUS_CHOICES = (
(STATUS_INACTIVE, 'Inactive'),
(STATUS_ACTIVE, 'Active'),
(STATUS_FINISHED, 'Finished'),
)
How to pass not numbers but this human readable values ('Inactive') to JSON above?