I was trying to fetch Django object in JSON format to my javascript variable. I have used from django.core import serializers predefined method available in Django, to convert it into JSON format. When I was trying to fetch that object directly into Jinja tag then it prints all the data, but when I was trying to get that data in Javascript variable then it won't work.
view.py
from django.http import HttpResponse
from django.shortcuts import render
from .models import Employee
from django.core import serializers
import json
def home(request):
data = serializers.serialize("json", Employee.objects.all())
return render(request,'home.html',{'data':data})
home.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
{% extends 'masterpage.html' %}
{% block content %}
**{{data | safe}}**(go below for output)
<form action="checkEmail" method="POST">
{% csrf_token %}
<input type="text" name="emailId" placeholder="Enter Email Id">
<input type="submit">
</form>
{% endblock %}
<p id="demo"></p>
<script type="text/javascript">
var data=eval('('+'{{data}}'+')');
var p=10;
document.getElementById("demo").innerHTML=p
console.log(p)
console.log(data);
alert(data);
</script>
</body>
</html>
Output : [{"model": "journal.employee", "pk": 1, "fields": {"ename": "Piyush Jiwnae", "eemail": "[email protected]"}}]
I can see the output for direct use of jinja tag in HTML but when I try to get that value in javascript variable it won't come and as shown in code I was trying to show that data and var p=10; document.getElementById("demo").innerHTML=p this value also not printed on console.