2👍
You can’t do this:
"sAjaxSource" : "{% url 'get_menu_list' '" + id + "' %}"
{% %}
are server-side directives. The server processes them and then puts them in the response page. The javascript function runs client-side. It can’t talk to the server and ask it for data in the way you have expected it to do here. You will have to do something that doesn’t depend on the server, such as:
"sAjaxSource": "/get_menu_list/" + id
0👍
I think you mixed up server side thing with client side. This piece
"{% url 'get_menu_list' '" + id + "' %}"
should be interpreted in server side. By then server side doesn’t know what is ‘id’ yet.
0👍
Then you could pass url as a variable to your function:
<script>
function initializeDataTable(data_url) {
var columnSize = $('table th').size();
$('#table').dataTable({
"sDom" : 'rtFip>',
'fnDrawCallback' : function() {
$('input:checkbox, input:radio').checkbox();
},
"bStateSave": true,
'sPaginationType' : 'full_numbers',
"bServerSide" : true,
"sAjaxSource" : data_url
});
}
$(function(){
initializeDataTable("{% url 'get_menu_list' item.id %}");
});
</script>
You could use tokens in your url:
<script>
var url_pattern = "{% url 'get_menu_list' '{id}' %}";
function initializeDataTable(id) {
var columnSize = $('table th').size();
$('#table').dataTable({
"sDom" : 'rtFip>',
'fnDrawCallback' : function() {
$('input:checkbox, input:radio').checkbox();
},
"bStateSave": true,
'sPaginationType' : 'full_numbers',
"bServerSide" : true,
"sAjaxSource" : url_pattern.replace('{id}', id)
});
}
$(function(){
initializeDataTable(42);
});
</script>
Notice that your token should match the regex type to resolve successfully (you can’t use {id}
as token if it’s defined with \d+
, instead use 0000
).
I was a little bit unsatisfied with this solution and I ended by writing my own application to handle javascript with django: django.js.
With this application, you can do:
{% load js %}
{% django_js %}
<script>
function initializeDataTable(id) {
var columnSize = $('table th').size();
$('#table').dataTable({
"sDom" : 'rtFip>',
'fnDrawCallback' : function() {
$('input:checkbox, input:radio').checkbox();
},
"bStateSave": true,
'sPaginationType' : 'full_numbers',
"bServerSide" : true,
"sAjaxSource" : Django.url('get_menu_list', id)
});
}
$(function(){
initializeDataTable(42);
});
</script>
To ensure that urls are loaded by Django.js, listen to the ready
event:
// Wait for document ready
$(function(){
initializeDataTable(42);
});
// Wait for Django ready
Django.onReady(function(){
initializeDataTable(42);
});
- [Answered ]-Integrate Visa and Mastercard in DJango 1.8 app
- [Answered ]-Django Models Abstract Base Class – can they be extended across apps?
- [Answered ]-Django: multiple values for keyword argument 'initial'
- [Answered ]-Nginx responds 404 for Django app but static files work
- [Answered ]-Django Querying MongoDB ObjectIds in views from json object