I am facing an issue accessing the primary key of a Django object serialized in JSON. Here is my JavaScript code:
function makeLink() {
recorder && recorder.exportWAV(function (blob) {
let fd = new FormData;
fd.append("audio", blob);
let csrftoken = getCookie('csrftoken');
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
/*console.log(obj[0].pk);*/
document.getElementById("result").innerHTML = obj.data[0]['pk'];
}
}
xhr.open('POST', uploadAudio_url , true)
//alert(uploadAudio_url)
xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.onload = function () {
// __log("Audio Uploaded to server succesfully");
};
xhr.onerror = function (e) {
// __log("Error Uploading audio" + e)
};
xhr.send(fd);
});
}
I am sending blob data, which represents an audio file, for speech processing on the backend. The backend filters the objects and responds with a queryset in JSON format. I am interested in extracting the primary keys of these objects to display images in a gallery grid.
Below is excerpt from my Views.py:
def process_speech(recognized_audio):
# Code block omitted for brevity
def upload(request):
# Code block omitted for brevity
The JSON data received looks like this:
[
{
"model": "Galeria.imagen",
"pk": 20,
"fields":
{"image_width": 6000,
"image_height": 4000,
"fichero_imagen": "files/img/lucas-albuquerque-615558-unsplash.jpg",
"keyword": [17, 18]}
},
{
"model": "Galeria.imagen",
"pk": 21,
"fields":
{"image_width": 5855,
"image_height": 3860,
"fichero_imagen": "files/img/freestocks-org-794156-unsplash.jpg",
"keyword": [18]}
}
]
I have attempted different methods to extract the primary key value but ended up with 'undefined' every time.
Your help is appreciated. Thanks in advance.