I have been having this problem for long. But I am not able to figure how to do this. Is there a way so, we can use the javascript objects with the template language. For example, I have queryset of categories which are rendered on a select widget.
Category: <select name="category" id="id_category">
{% for category in categories %}
<option value="{{category.id}}">{{category.name}}</option>
{% endfor %}
</select>
Now, for the selected category, I asynchronously call the server to return the related Product Types.
$('#id_category').change(function(){
getProductTypes($(this).val());
});
In the ajax function, I am unable to use the category_id js object in the url template tag. Due to this I am bound to hard code the target url. Can anyone please suggest a way to handle this. Thanks
function getProductTypes(category_id){
//Would like to do this
var url = {% url lookup_product_types category_id %}
//But end up doing this
var url = '/'+category_id+'/product_types/find/'
$.ajax({
url:url,
data:{category:category_id},
dataType:'json',
success: function(data, status, xhr){
html = '<select>';
$.each(data, function(index, value){
html += '<option value='+this.pk+'>'+this.fields.name+'</option>';
});
html += '</select>';
$('#productType').html(html);
}
});
How about using a data attribute on the option tags?
You would update your template to something like –
Then change the ajax along the lines of –