Question

I am doing as simple as trying to fetch a single object and display it as follows:

View:

def sample(request,faculty):
    faculty_details = Faculty.objects.get(username=faculty)
    faculty_json=serializers.serialize("json",[faculty_details])
    faculty_json = faculty_json.strip("[]")
    return HttpResponse(json.dumps({'faculty':faculty_json}), mimetype="application/json")

Template:

$.getJSON(url, function(data) {
    faculty=data['faculty'];
    alert(faculty.fields['username']);    //this does not work!!
}

I have wasted a good amount of time here. I want to know what I am doing wrong?

Was it helpful?

Solution

Well, faculty_json is already json, because it is created by the json serializer. So I don't understand why you are then dumping it again to JSON in the return statement. That will simply double-encode the quotes, so Javascript now sees it as a string rather than an actual JSON object.

Remove that json.dumps and all should be fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top