Using passed in variables in Datatables from Django framework
Using passed in variables in Datatables from Django framework
Hi all.
I know these kind of questions get asked a lot, but I cannot find a good example using the newer API. Basically I am using the Django framwork and would like to populate my DataTable with a data that was generated in a view.
Within my view I have a list of dictionaries. I cannot work out how to get this to be used as the data to a Datatable. I have also tried passing in JSON (json.dumps(dataSet)), but still cannot get the table to use this as a data source.
I have re-written this as a very basic example, almost pinched directly from this site and using an array of arrays rather than a dictionary - but still hitting the same issues.
If I don't pass the data into the template and instead define it directly in the javascript this works ok.
The result is an empty, non styled/formatted table (i.e the CSS etc has not worked either), however if I look at the page source I can see that the data from the view has been passed through.
Any ideas what I am doing wrong? I am finding this very frustrating.
My view.py:
def test(request):
dataSet = [
[ "Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800" ],
[ "Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750" ],
[ "Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000" ],
];
return render(request, "test.html", {'dataSet' : dataSet })
My template:
<!doctype html>
<html>
<head>
{# jQuery #}
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
{# datatables.js #}
<script type="text/javascript" charset="utf8" src="http://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.9/css/jquery.dataTables.css">
{# CSS #}
<link rel="stylesheet" href="/static/style.css" type="text/css" />
<title>DataTables Test</title>
</head>
<body>
<header>
<h1>DataTables Test</h1>
</header>
<script>
$(document).ready(function() {
$('#example').DataTable( {
data: {{dataSet}}, <!-- trying to use the passed in variable-->
columns: [
{ title: "Name" },
{ title: "Position" },
{ title: "Office" },
{ title: "Extn." },
{ title: "Start date" },
{ title: "Salary" }
]
} );
} );
</script>
<section>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
</section>
</body>
</html>
Answers
Ah realised my mistake. Even though I can pass the JSON from the python view to the template. I am not correctly parsing the JSON on the template side. Needed to add var dataSet = JSON.parse( '{{dataSet | escapejs }}'); within the js.