I have below code that sends id to my django view and gets couple of json objects from the server, this is working but I couldn't use the response objects in the template i.e., json objects but only one object with the context names only in my http service success function.
Here is the view code -
def preview(request): if request.method == "POST": response_data = {} try: data=json.loads(request.body.decode()) v_pid=data["id"] basic_v_obj = tsbasicinfo.objects.get(emailid = request.session.get('emailid')) if tswex.objects.filter(pid = v_pid).exists(): wc_v_obj = tswex.objects.filter(pid=v_pid) wc_v_qs = tswex.objects.filter(pid=v_pid) wc_v_json_list = [obj.as_dict() for obj in wc_v_qs] else: wc_v_obj ='' wc_v_json_list='' context = { 'js': basic_v_obj, 'jjs':wc_v_obj, } context['wc_V_json'] = mark_safe(json.dumps(wc_v_json_list, ensure_ascii=False)) except: context = {'status': "nodata"} return HttpResponse(context, content_type="application/json")
Here is the http service function using AngularJS:
$scope.preview_ang = function (clicked_id) { $http({ method: 'POST', url: 'pvcan', data: { 'id': clicked_id }, headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .success(function (data) { if (data == "null") { alert('server returned nothing but success'); } else { alert(JSON.stringify(data,null,2)); jdata = data['wc_V_json']; alert('First Sk: '+JSON.stringify(jdata)); // displays unknown.. as data is just a string object containing context names :( } }) .error(function (data, status, headers, config) { alert('server returned error :'+status); }) }
When I keep breakpoint in the view while returning HttpResponse, I can see the objects with the data that am expecting, however I am not sure how to make use of it in the javascript inside template.
When I use render_to_response method, I could use the response context as below for example -
jdata_wc = {{ wc_V_json|safe }};
How can I use the same way in my template when I return the data using HttpResponse from the view ?