Rajiv Gupta Rajiv Gupta - 3 months ago 47
JSON Question

Django: send json response from view to a specific template

The main requirement is to send a json object from django view to a specific template named output.html (already present in templates directory), as a part of response. Also, the json response contains model and pk attribute, I want to remove them and send only the fields json attribute.

When I try as follows :

def view_personal_details (request):
personal_detail_json = personal_details.objects.all()
personal_detail = serializers.serialize('json', personal_detail_json)
return HttpResponse (serializers.serialize('json', personal_detail_json), content_type='application/json');


I get json in a new page.

And when I try as follows :

def view_personal_details (request):
personal_detail_json = personal_details.objects.all()
personal_detail = serializers.serialize('json', personal_detail_json)
return render (request, "webFiles/output.html", {'personal_detail': personal_detail})


I have to access the data via {{ personal_detail }} in my html, and not from response.

Also, the json response is as follows :

[
{
model: "buglockerApp.personal_details",
pk: "001",
fields: {
name: "Rajiv Gupta",
email: "rajiv@247-inc.com",
doj: "2016-06-22",
dob: "2016-06-22",
address: "Bangalore",
contact: "9902384347"
}
}
]


I don't want the model and pk to be sent as the response. Only fields should be sent as a part of response to webFiles/output.html file.

Thanks in advance!!

Answer

you can do the following in python2.7

import json
def view_personal_details (request):
    personal_detail = serializers.serialize('json', personal_details.objects.all())
    output = [d['fields'] for d in json.loads(personal_detail)]
    return render (request, "webFiles/output.html", {'personal_detail': output})

or you can read the following for more clarification
https://docs.djangoproject.com/en/1.10/topics/serialization/#serialization-of-natural-keys
https://github.com/django/django/blob/master/django/core/serializers/base.py#L53