I am utilizing a Django QuerySet as a JSON response within a Django view.
def loadSelectedTemplate(request):
if request.is_ajax and request.method == "GET":
templateID = request.GET.get("templateID", None)
template = list(operationTemplates.objects.filter(templateID = templateID))
if operationTemplates.objects.filter(templateID = templateID).exists():
ser_template = serializers.serialize('json', template )
return JsonResponse({"valid": True, "template": ser_template}, status=200)
else:
return JsonResponse({"valid": False}, status = 200)
The JSON response is then captured by JavaScript and can be viewed in the console.
// Perform a GET AJAX request
$.ajax({
type: 'GET',
url: "{% url 'loadSelectedTemplate' %}",
data: {"templateID": templateID},
success: function (response) {
// If valid template, append to textarea
if (response["valid"]){
var template = response["template"];
console.log(response);
}
This is how the JSON object appears in the console log;
{
"valid": true,
"template": "[{\"model\": \"opnoteannotator.operationtemplates\",
\"pk\": 14,
\"fields\": {\"templateCategory\": \"Lower Limb\",
\"templateName\": \"Femoral to below knee Bypass using autologous vein\",
\"templatePreopBundle\": \"WHO check list completed.\\r\\n
Antibiotic Chemoprophylaxis: Co-amoxiclav / Teicoplanin / Gentamicin\",
\"templateIndication\": \"CLTI with night pain / rest pain / tissue loss / infection\",
I aim to extract the values under "fields" and display them into a text-area on my website. Can someone guide me on how to achieve this? I have attempted various methods, but unable to access the values in JavaScript.
Thank you for your assistance in advance.