Passing Python Objects to JavaScript through Django Template Variable - javascript

I have been able to pass primitive types such as integers like this, but I would like to pass more complicated objects, such as some the Django models that I have created. What is the correct way of doing this?

I know I'm a little late to the party but I've stumbled upon this question in my own work.
This is the code that worked for me.
This is in my views.py file.
from django.shortcuts import render
from django.http import HttpResponse
from .models import Model
#This is the django module which allows the Django object to become JSON
from django.core import serializers
# Create your views here.
def posts_home(request):
json_data = serializers.serialize("json",Model.objects.all())
context = {
"json" : json_data,
}
return render(request, "HTMLPage.html",context)
Then when I'm accessing the data in my html file it looks like this:
<script type = 'text/javascript'>
var data = {{json|safe}}
data[0]["fields"].ATTRIBUTE
</script>
data is a list of JSON objects so I'm accessing the first one so that's why it's data[0]. Each JSON object has three properties: “pk”, “model” and “fields”. The "fields" attribute are the fields from your database. This information is found here: https://docs.djangoproject.com/es/1.9/topics/serialization/#serialization-formats-json

For Django model instances in particular, you can serialize them into JSON and use the serialized value in your template context.
From there, you can simply do:
var myObject = eval('(' + '{{ serialized_model_instance }}' + ')');
or
var myObject = JSON.parse('{{ serialized_model_instance }}');
if using JSON-js (which is safer).
For Python objects in general see How to make a class JSON serializable

Related

Passing Json from Django view to template Javascript [duplicate]

In views.py, I have time series data stored in a dictionary as follows:
time_series = {"timestamp1": occurrences, "timestamp2": occurrences}
where each timestamp is in unix time and occurrences is an integer.
Is there a way to pass the time series data as a json object in the context of the render function?
Why do this: I am using Cal-heatmap on the front end which requires the data to be in json format. Ajax requests work just fine for now but I ideally would like to use the render approach if possible.
If a frontend library needs a to parse JSON, you can use the json library to convert a python dict to a JSON valid string. Use the escapejs filter
import json
def foo(request):
json_string = json.dumps(<time_series>)
render(request, "foo.html", {'time_series_json_string': json_string})
<script>
var jsonObject = JSON.parse('{{ time_series_json_string | escapejs }}');
</script>
Pass a json.dumps value to the template. It is already a valid JSON string so you don't need to parse it or anything. Only when rendering it in the template, mark it as safe to prevent HTML quoting.
# views.py
def foo(request):
time_series_json = json.dumps(time_series)
return render(request,
"template.html",
context={'time_series': time_series_json})
# in the template
<script>
const timeSeries = {{ time_series | safe }};
</script>
Using the Django templates built-in filter json_script:
In views.py:
render(request, "foo.html", {'time_series_data': time_series})
In the template foo.html:
{{ time_series_data|json_script:"time-series-data" }}
In your script:
const timeSeriesData = JSON.parse(document.getElementById('time-series-data').textContent);
have you tried passing something like json.dumps(time_series) to the render function?

How to save Json in the django database from Javascript

I will generate a json and save it in a string variable, and I need to save the whole json in my database.
I have a view
class DashboardView(TemplateView):
template_name = 'votes/dashboard.html'
in this template, I have javascript, and in this javascript I'm generating Json and saving it in a js variable, and I want to put the json in the variable into the DB.
As I'm gonna create a object for the jsons, I'll change templateview to CreateView as It's gonna save.
But how is this json going to become available for the view to be saved ?
brief instruction
using jquery ajax:
$.post( "/your/url/for/store/json/data", { jsonField: jsonData } );
in your view:
def save_json_data(request):
...
data = request.POST.get("jsonField", "")
model = YourModel(json_field=data)
model.save()
...

JSON to JS with Django: SyntaxError: missing : after property id

I'm attempting to get a JSON file into a script. I can't seem to be able to get it there by serving it from the filesystem so I made a view that returns the JSON data to the page like so:
def graph(request, d): #d.data is the file in the database
data = json.load(d.data)
return render(request, 'temp/template.html', {'json': data})
In my JS:
var j = {{ json|safe }};
When I look at the source for the JS it shows the data in this format:
{u'people': [{u'name': u'steve'}, {u'name': u'dave'}]}
Which I read shouldn't be a problem. I don't have any variables called 'id' and yet I get the error in the title pointing to the provided line of JS.
Why could this be? Also how do I then use the objects from the JSON in my script?
Solved by using simplejson:
import simplejson as json
And everything else as above. This is because the built in json.dumps returns an array of unicode like:
{u'people': [{u'name': u'steve'}, {u'name': u'dave'}]}
When using simplejson that shouldn't be a problem.

Accessing Django dictionary in Javascript

I'm passing a dictionary from my Django view and want to access the dictionary in my code.
view code:
res.responses is a dictionary
def index(request):
import pprint
pprint.pprint(res.responses)
print 'type = ', type(res.responses)
return render_to_response("deploy/index.html", {"responses":res.responses})
Javascript code:
$(document).ready(function(){
//{% for each in responses%}
// console.log(Hi)
//{% endfor %}
var response = "{{responses}}"
console.log(response)
I tried accessing the variable directly using for loop and also accessing the variable directly. Both throw me an error. Please provide some suggestion.
You can do both.
Option 1:
Provide the script via a template that will send the code with the values. Will look ugly but work. Your javascript file or even the html must be parsed by the django template engine. They can't be static
Option 2:
Provide a new view with a json response, that is accessed from your javascript code (ie: via JQuery)

Passing json object to python using angularjs

I'm new to angularjs and python and I have this problem. I've been trying to pass in the data of a form to Python server side using angularjs. I've converted the form to a json object before sending it over in my .js controller.
controller.js:
jsonObj = this.form.toJson;
$xhr('POST','/form/processform',jsonObj,function() {
alert("Done!");
window.load("/");
}, function(){
"Request failed";
});
Python:
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import simplejson as json
class processForm(webapp.RequestHandler):
def post(self):
form = json.loads(self.request.body)
# process forms
self.redirect("#/")#redirects to main page
I recieved an error called "JSONDecodeError: No JSON object could be decoded". I've tried to replace the 'POST' to 'JSON' but it does not seem to work as well. I've also read up on $resource in angularjs, but i'm not sure how to use it.
Is this because of the wrong usage of $xhr? Any help will be greatly appreciated! :)
Acording to JSONDecodeError the jsonObj variable is not containing a valid JSON object.
I believe problem is here:
jsonObj = this.form.toJson;
You shoud call the toJson method instead of assiging it to a variable:
jsonObj = angular.toJson(this.form);

Categories

Resources