I know that the Jinja2 library allows me to pass datastore models from my python code to html and access this data from inside the html code as shown in this example . However Jinja2 isn't compatible with javascript and I want to access the data inside my Javascript code . What is the simplest templating library which allows to iterate over my datastore entities in Javascript ? I've heard about things like Mustache and Jquery , I think they look a bit too complicated. Is there anything simpler?
You should create a python controller which serves JSON formatted data, which any Javascript library (especially jQuery) can consume from. Then, setup the Jinja2 template to contain some Javascript which calls, loads and displays said data.
One more approach to consider: If the Python object is not dynamic, you may want to use json.dumps() to store it as a TextProperty, and simply JSON.parse(unescape(model_text)) on the JS side. Reduces the overhead, and memory hit which can be important when trying to stay within an F1 limit. For example, I run an instance that very easily runs inside an F1. There is one large dictionary object that we deliver. Were this object to exist as a Python dictionary inside the instance we would kill the instance due to the soft memory limit. Using the TextProperty approach we can pass this large dict to the client without any issues. (Note: we did have to momentarily boost our instance up to an F4 when initially creating this object -- something incredibly easy inside the Admin web page.) With more dynamic objects, answers above apply.
Jinja2 and Javascript play fine together. You need to arrange to have template expansion emit your Python data structures into a JS-friendly form.
https://sites.google.com/a/khanacademy.org/forge/technical/autoescape-in-jinja2-templates covers it fairly well. (Note the use of the escapejs filter.)
It works. I had to serialize(convert) my datastore entities to json format, which Javascript understands well. I created a function which converts every instance of my datastore into a dictionnary then encapsulates all these instances into a list which is then converted to Json using json.dumps. When I pass this result to the Java script , I can then easily access my values as seen below.
import json
import webapp2
from google.appengine.ext import db
import jinja2
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'],
autoescape=True)
# serialize datastore model to JSON format
def serialize(model):
allInstances = model.all() # fetching every instance of model
itemsList = [] #initial empty list
for p in allInstances:
d = db.to_dict(p)
itemsList.append(d)
return json.dumps(itemsList)
class myModel(db.Model):
v = db.FloatProperty()
c = db.FloatProperty()
tdate = db.DateTimeProperty(auto_now_add=True)
class MainPage(webapp2.RequestHandler):
def get(self):
myModel(v=4.5, c=3.0).put()
#creating template variables
template_values = {
'json_data': serialize(myModel)
}
template = JINJA_ENVIRONMENT.get_template('index.html')
self.response.write(template.render(template_values))
Inside my 'index.html' file, I have:
{% autoescape true %}
<!DOCTYPE html>
<html>
<head>
<title> webpage </title>
<script type="text/javascript">
// I retrieve my data here
var results = "{{ json_data }}";
for(var i = 0; i < db_results.length; i++) {
document.write("myModel instance:" + i + results[i] + "<br>");
}
</script>
</head>
<body>
</body>
</html>
{% endautoescape %}
It has nothing to do with compatibility. Jinja is server side templating. You can use javascript for client side coding.
Using Jinja you can create HTML, which can be accessed by javascript like normal HTML.
To send datastore entities to your client you can use Jinja to pass a Python list or use a json webservice.
Related
I'm new to working with django and I am trying to send information to my clientside javascript. I have a list of FooBarModels that I want to use with my clientside Javascript. Currently, I'm using the django template to generate an array of dictionaries that holds the information I'll use with the Javascript.
This feels like a hacky solution, is there a better way to achieve this?
models.py
class FooBarModel(models.Model):
bar = models.ForeignKey(Bar, on_delete=models.CASCADE)
#property
def desc(self):
# logic here
#property
def display_name(self):
# logic here
template.html
<script>
var $fb_list = [
{% for fb in foobar_list %}
{ "name": {{fb.display_name}}, "desc": {{fb.display_name}} },
{% endfor %}
]
// a bunch of code that uses the $fb_list
</script>
What's the best practice for handling this type of situation? Should I be sending a package of JSON to the clientside and parsing it?
This is called Serialization, Which means converting a django django.db.Model to JSON, the inverse of this is called Deserialization which means converting the JSON to a native object, this time -if it's a valid object-.
Django supports it natively, And DRF extends this support.
Here's an example with django itself.
from django.core import serializers
data = serializers.serialize("json", SomeModel.objects.all()) # xml is supported too
print(data) # prints model as JSON
or
JSONSerializer = serializers.get_serializer("json")
json_serializer = JSONSerializer()
json_serializer.serialize(queryset)
data = json_serializer.getvalue()
print(data)
It needs a queryset EVEN if you are serializing a single object.
I've hit a bit of a stumbling block with a Django project having added a chart to a page using Chart.js only to find that it relies on the data inputted being in JSON format. I've researched ways of converting Django object values into JSON, such as serializing and re-writing my views, but for a number of reasons these aren't ideal options for me. Is there a way to convert Django object data to JSON data within the JS script?
I have an 'Accelerator' Django model with five separate decimal fields which ultimately need to be converted to JSON to feature in the chart. For each object created, the value of each field is prone to change (they are determined by a method calculating the mean value of separate values inputted into a separate model). I have an 'accelerator_detail' HTML template which renders and displays the various values of individual objects created using the Accelerator model.
This template is heavily reliant on Django placeholders and Python logic calling on object values, which is one reason why I'm hesitant about attempting to serialize the Django objects as JSON within my views (presumably this would mean I would have to re-write this template).
I've shared some of the relevant code below to provide a better understanding. Currently, the data key in my JS script is populated with dummy data but this is where my Django object values need to be stored:
// One of my model fields which needs converting to JSON
class Accelerator(models.Model):
avg_mentorship = models.DecimalField(decimal_places=2, max_digits=3)
#property
def avg_mentorship(self):
quantity = Review.objects.filter(subject=self)
mentorship_result = Review.objects.filter(subject=self).aggregate(avg_mentorship=Avg('mentorship'))['avg_mentorship']
return mentorship_result if len(quantity) > 0 else 0
// My accelerator_detail view
def accelerator_detail(request, pk):
accelerator = get_object_or_404(Accelerator, pk=pk)
reviews = Review.objects.all()
context = {
'accelerator': accelerator,
'reviews': reviews,
}
return render(request, 'reviews/accelerator_detail.html', context)
// JS script within my HTML template
<script>
var myChart = document.getElementById('accRatings').getContext('2d');
var ratingsChart = new Chart(myChart, {
type:'horizontalBar',
data:{
labels:['Mentorship', 'Hiring', 'Community', 'Fundraising', 'Corporate Development'],
datasets:[{
data:[
4.1,
4.4,
3.9,
3.6,
4.2
],
}]
},
});
</script>
Sorry I can't give this in a comment yet, have you looked into this yet? Django Generic JSON views. Seems to me like it would fit nicely into your project and help with the output you need.
Your data is already output by the view. You can just convert to JSON as you serve it from within the view.
Great example provided by SimpleIsBetterThenComplex:
from django.http import JsonResponse
def profile(request):
data = {
'name': 'Vitor',
'location': 'Finland',
'is_active': True,
'count': 28
}
return JsonResponse(data)
I see some relevant posts to my query.
Tornado is used in the below link
How to pass variable from python to javascript
I know that it can be done using json but I am not clear how to implement it.
In the web2py default controller I am returning a dictionary which contains the latitudes and longitudes.
def index():
lat_long_list=[]
info1 = {'lat':'1.0032','long':'2.00003','name':'Akash'}
info2 = {'lat':'1.2312','long':'-1.0034','name':'Kalyan'}
lat_long_list.append(info1)
lat_long_list.append(info2)
return dict(lat_long_list=lat_long_list)
In java script I want to iterate through the list of dictionaries and mark the points on the google maps.
I cannot say
<script>
{{ for lat_long_rec in lat_long_list :}}
var name = {{=lat_long_rec['name']}}
{{ pass }}
</script>
This fails. An alternative to handle this is to write the list into an xml and from javascript read the file but I dont want to achieve it this way as writing to file is non performant. Let me know how best this can achieved.
Convert the Python list to JSON and pass that to the view to insert in the Javascript code:
from gluon.serializers import json
return dict(lat_long_list=json(lat_long_list))
In the view:
<script>
...
var latLongList = {{=XML(lat_long_list)}}
...
</script>
I'm trying to pass a string of generated HTML from Python to Javascript. This is the simplified version of my view (using Pyramid framework).
#view_config(route_name='view_page', renderer='templates/page.jinja2', permission='view')
def view_cosmeceutical(request):
gen_html = markdown( ingredient.desc )
return dict(gen_html=gen_html)
From this thread, I saw that I can use {{ variable }} in Javascript too, so in my JS file, I have a function that attempts to change the innerHTML of the element with the id 'content-desc'. But all I'm getting is the string {{ genHTML }} instead of the actual variable containing the generated HTML.
function insertHTML() {
genHTML = '{{gen_html}}';
$('#content-desc').html(genHTML);
}
What am I doing wrong?
One good way to pass data and content from the server-side Python to JavaScript are
JSON embeds in HTML
Separate AJAX calls which serve JSON objects as application/json mime
For the embed approach, I would do somethibng along the lines to export data to the page template as JSON:
import json
gen_html = ...
javascript_data = json.dumps(dict(gen_html=gen_html))
return dict(javascript_data=javascript_data)
Then in the page template pass this to JavaScript global variables:
<script>
window.javascriptData = {{javascript_data}}; // Check need to escape HTML in your case
</script>
And then in JavaScript (keep preferably in a separate static .JS file):
$(document).ready(function() {
$('#content-desc').html(window.javascriptData.gen_html);
});
Also, I would not generate HTML for just passing it to JavaScript in the first place. Instead, I would pass raw data to JavaScript as JSON, and then generate HTML on the client-side from this data using client-side templating. This increases the complexity, but is more "clean" and flexible.
Example microtemplating engines for the client-side JavaScript:
DOM tree based JavaScript template engines
I want to build a stock website with Django, and I found a Javascript library (tickp) to make charts, but I don't know Javascript, nor do I know how to read json data in a Django template. I use this code to retrieve the stock data from Yahoo Finance.
I put these .py and .js in my folder, and my views like this:
from stock.stockretriever import StockRetriever
def stockretriever(request,number):
data = StockRetriever().get_historical_info('YHOO')
return HttpResponse(simplejson.dumps(data),mimetype='application/json')
But I don't know how I should write the template, can somebody tell me?
thanks.
You have two options:
render a template with data included
dynamically fetch data from the server
If you go for 1. you could add something like this to your template:
<script type="text/javascript">
var my_data = {{ json_plot_data }};
</script>
The template includes also the javascript code that generates the plots from the data. The view function would include the data fetching and return a context object like so:
def my_stock_plot_view(request, number):
# get stock data
json_data = simplejson.dumps(data)
django.shortcuts.render(request, 'template.html', {'json_plot_data':json_data})
If you go for 2. you would need to use something like jQuery.ajax to dynamically load json data using an ajax request. That request would invoke your view, in the jQuery.ajax call you specify that the request returns JSON which automatically makes the data available as an object to Javascript. In the jQuery.ajax success handler you would pass the data to your plot function.
I don't have these libraries installed, but based on the readme of the tickp library, you'll need the following data: [date, open, high, low, close and optionally volume]. The get_historical_info function returns the columns [Date, Open, High, Low, Close, Volume, AdjClose]. The mismatch here is the AdjClose, so you'd need to strip that from the data you get from the StockRetriever:
from django.shortcuts import render
from stock.stockretriever import StockRetriever
def stockretriever(request, number):
data = StockRetriever().get_historical_info('YHOO')
# Assuming data is returned as a list of lists
new_data = [d[:-1] for d in data]
return render(request, 'stock.html', { 'data': simplejson.dumps(new_data) })
Following along with the readme, you need something along the following lines in your template:
<html>
<head><script src="tickp.js"></script><script src="stats.js"></script></head>
<body onload='plot = window.tickp("#chart"); plot.read({{ data }}); plot.plot();'>
<div id="chart"></div>
</body>
</html>
Note that I've cut some corners with respect to possible Ajax calls or proper formatting and usage, but it should give you something to get started with. When you're missing something, please update your question with the specific issues you're having.