In my django project i make an ajax call for dynamically display and populate fields. First of all, in my template i create the element:
Template html
<select class="form-control" onChange="AddOptions(this);">
{% for entry in all_test %}
<option id="mainID" value="{{ entry.id }}">{{ entry.descr }}</option>
{% endfor %}
</select>
<div id = "div_val" class="input-group" style="display: none;">
<div class="input-group-btn">
<button id = "btn_val" type="button" class="btn btn-danger">Test</button>
</div><!-- /btn-group -->
<input type="text" class="form-control">
</div>
then in my js:
start.js
function AddOptions(VarID) {
$.ajax({
type: "POST",
url: "ajax",
data: {mainID: VarID.value},
success: function (data) {
$.each(data, function (index) {
$("#div_val").show();
console.log("Key: " + data[index].OptionKey+" Val: "+ data[index].OptionVal)
});
}
});
}
urls.py
url(r'^ajax$', mainoptions),
and finally my python function called from urls.py:
from frontend.models import temp_main, temp_case, temp_variables
def mainoptions(request):
if request.is_ajax():
mainOptions = temp_variables.objects.filter(main_id=int(request.POST['mainID']))
response = []
for i in mainOptions:
vallabel = {}
vallabel['OptionID'] = i.id
vallabel['OptionKey'] = i.v_key
vallabel['OptionVal'] = i.v_val
response.append(vallabel)
json = simplejson.dumps(response)
return HttpResponse(
json, content_type='application/json'
)
else:
pass
All done, my hidden div "div_val" in template was show, but now i can't understand how can i use the returned data in my template, for, for example, populate the value of the element inside the div (without using jquery inside my js func for do it). How can i close the chain Template -> js -> urls -> view method -> Template ?
Many Thanks in advance