Incorporating Javascript into a Django template: best practices

Using Django templates, I am interested in embedding a Bokeh plot by using Json output.

The Json output is already prepared for querying the database. The plot needs to be displayed in a div with a specific ID.

According to the documentation, the following code function should be used to utilize the Json output in the template:

item = JSON.parse(item_text);
Bokeh.embed.embed_item(item);

I need guidance on the correct syntax for implementing this in the template:

<div id="title"></div>

<script>
function(response) { return item = JSON.parse( {{plot_json}} ); }
function(item) { Bokeh.embed.embed_item(item); }
</script>

View file:

def home(request):
    plot_json = Price_Charts.objects.using('llweb').values('timeframe_1h').filter(symbol_pair='ETH')
    context = {
    'plot_json': plot_json
    }
    return render(request, "home.html", context)

Answer №1

While my knowledge of Bokeh is limited, I do know that it's important to make sure the JSON object is interpreted correctly in a Django template as JavaScript and not auto-escaped. One way to achieve this is by trying out disabling autoescaping in combination with using the Bokeh 'then' syntax.

<div id="title"></div>

<script>        
fetch('/plot') 
    .then(function(response) { 
         {% autoescape off %}
             return item = JSON.parse( {{plot_json}} ); 
        {% autoescape on %}
    })
    .then(function(item) { Bokeh.embed.embed_item(item); })
</script>

Answer №2

If you're looking for a simplified jinja2 example that works with Bokeh v1.0.4, give this code snippet a try:

python myapp.py

Here's how your file and directory structure should look like:

myapp
   |
   +---myapp.py
   +---templates
        +---index.html 

In your myapp.py file:

import io
import json
import jinja2
import numpy as np
from bokeh.plotting import figure, curdoc
from bokeh.embed import json_item
from bokeh.resources import CDN

plot = figure()
plot.line(np.arange(10), np.random.random(10))
curdoc().add_root(plot)

renderer = jinja2.Environment(loader = jinja2.FileSystemLoader(['templates']), trim_blocks = True)
html = renderer.get_template('index.html').render(resources = CDN.render(), item_json_object = json.dumps(json_item(plot)))

filename = 'json_items.html'
with io.open(filename, mode = 'w', encoding = 'utf-8') as f:
    f.write(html)

Your index.html file:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
{{ resources }}
</head>
<body>
<div id="myplot"></div>
<script>
    Bokeh.embed.embed_item({{ item_json_object }}, "myplot");
</script>
</body>
</html>

When using json.dumps(json_item(plot) in the template, be aware that it's already a JSON object, so no need to use JSON.parse() on it. Ensure you pass a string object if needed.

You can find more details in the Bokeh documentation, which includes an example showcasing dynamically loaded plot data through JS fetch() method at page loading time compared to attaching plot data during template rendering.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it recommended to keep static files in a dedicated S3 bucket while deploying using AWS Elastic Beanstalk?

I am currently running a Django app on AWS Elastic Beanstalk. The platform has created an S3 bucket to house the source code, versions, and other data. I have set up the S3 bucket to also store my static files. However, with each new code deployment, the ...

Tips on populating the gap between dual cylinder meshes in Three.js

I'm working on a code that creates cylinders using a series of 3D vectors, but I'm encountering an issue with unsightly gaps between them: https://i.sstatic.net/E17Gm.png Does anyone have any tips on how to fill in these gaps in the latest vers ...

Activate ajax search in select2 by hand

I recently integrated the select2 plugin with jQuery into my website. For the most part, it functions perfectly. One particular feature I have is a search widget that utilizes select2 and remote data search. When I enter a search query using a keyboard ...

Validating decimals in a text field with either JavaScript or jQuery

I need to implement text field validation on the keyup event. The text field should only accept money type decimals such as: (12.23) (.23) (0.26) (5.09) (6.00) If any incorrect value is entered, it should revert back to the previous value and remove the ...

Which one should I use: ng-repeat or ng-options?

I am looking to display JSON data in a dropdown list, and I have two options to choose from. The first option is using ng-repeat, while the other option is ng-options. Using ng-repeat: In the HTML file: <select> <option ng-repeat="prod in testA ...

A quicker method for deleting an element from an array based on its index

Last year, I posted this and now I feel there could be a simpler solution. I am looking to remove an item from an array based on its index. Even if the array contains duplicate values, I want to be able to remove the item by its index. Here is a common ex ...

Determine the absence of values in a randomly generated array and identify the quantity of missing values

My current challenge involves solving CodeSignal projects, and I recently encountered a problem where a random array of numbers is given, requiring me to determine how many additional numbers are needed to make the array consecutive. For instance, if the ...

Merge topics together in RxJS like zip

Is it possible to create an observable that combines two subjects in a unique way, different from the zip function? The goal is to combine two subjects so that when both have emitted values, the latest of their values is emitted. Then, after both emit at ...

Creating a highly innovative server infrastructure tailored for Dojo applications with exceptional features

Recently, I have been using web2py for my projects and have found it incredibly useful in creating RESTful web applications. However, I am now looking to expand my skills in JavaScript by developing a more modern and dynamic client-side application that re ...

The Art of jQuery Data Processing

I'm currently working on extracting data from a form submission. Below is the code I've been using. function handleSubmission() { $("#questionForm").submit(function() { $.post("SubmitQuestion.php", $("#questionForm").serialize()).done(functi ...

Exploration of features through leaflet interaction

Attempting to plot bus routes on a map using leaflet with geojson for coordinates. Facing issues with making the bus line bold when clicked, and reverting the style of previously clicked features back to default. Current Progress function $onEachFeature( ...

extract information from the request header

One of the functionalities in my application involves making Ajax requests to the server. $.ajax({ type: "get", beforeSend: function (jqXHR) { jqXHR.setRequestHeader(ZO_KEY1, _key1); jqXHR.setReq ...

Generating a dynamic form by utilizing a JavaScript JSON object

I need assistance with creating an html form based on a JSON object’s properties. How can I target multiple levels to generate different fields and also drill down deeper to access field details? I am open to suggestions for alternative formats as well. ...

Is utilizing Eval on a div within a DataList ItemTemplate feasible for MouseOver event handling?

Apologies for the complicated title. Here is the structure of my DataList: <asp:DataList ID="DataListFloor" runat="server" RepeatColumns="5" > <ItemTemplate> <div style='width:199px;height:166px;background-color: <%# Ev ...

Vue: the parent template does not permit the use of v-for directives

Upon creating a simple post list component, I encountered an error when trying to utilize the v-for directive: "eslint-eslint: the template root disallows v-for directives" How can I go about iterating through and displaying each post? To pass data from ...

To ensure that new tabs are opened directly within jQuery UI tabs, the tab should be created within the jQuery UI tabs interface

I have integrated jquery-UI to create a dynamic Tab panel. When I click on the "Add Tab" button, a new tab is created. However, the new tab does not open automatically. It only opens when clicked on. $(function() { var tabTitle = $( ...

Check if an object is already in an array before pushing it in: JavaScript

Summary: I am facing an issue with adding products to the cart on a webpage. There are 10 different "add to cart" buttons for 10 different products. When a user clicks on the button, the product should be added to the this.itemsInCart array if it is not a ...

Loading information in a directive by utilizing promises in a service with AngularJS

Can anyone lend a hand? I've been struggling to solve this issue. I created a directive (see below) to display a pre-written ul-list on a page using html data fetched asynchronously from a database server. Both the Directive and The Service are funct ...

Need help setting up a time-based query in Laravel? Here's how to schedule it!

I am currently using the following query to update a status value. public function updateStatus(Request $request) { $customer = Customer::findOrFail($request->user_id); $customer->status = $request->status; $customer->new_customer_s ...

Vue 2 checkbox form array data

Creating a checkbox list with a dynamic id and name: Data: yards[{id:1,name:'test'}] etc HTML: <ul class="checkbox-list"> <template v-for="(yard, index) in yards"> <li> ...