Displaying D3.js Chart with Django Backend - javascript

I am learning to build dashboard using Django as backend and D3.js for visualization.
Following is my index.html:
{% load static %}
<html>
<script src="https://d3js.org/d3.v7.min.js"></script>
<body>
<h1> Hello! </h1>
<script src={% static "js\linechart.js" %}>
var data = {{ AAPL|safe }};
var chart = LineChart(data, {
x: d => d.date,
y: d => d.close,
yLabel: "↑ Daily close ($)",
width,
height: 500,
color: "steelblue"
})
</script>
</body>
</html>
Data AAPl is extracted from database and the views.py is as follows:
from django.shortcuts import render
from django.http import HttpResponse
from cnxn import mysql_access
import pandas as pd
# Create your views here.
def homepage(request):
sql = ''' select Date, Close from tbl_historical_prices where ticker = 'AAPL' '''
cnxn = mysql_access()
conn = cnxn.connect()
df = pd.read_sql(sql, con=conn)
context = {'AAPL':df.to_json()}
return render(request, 'index.html', context=context)
Function line chart can be viewed here which is being used in js\linechat.js in index.html file.
I can see the Hello! being displayed on the page but can't see the line chart. I am unable to debug the problem. No errors found in console tab either.
How can I display the line plot?
I've added the current page display in attached image.

Close off your script with a src and start a new script tag. The presence of src precludes internal code.
<script src={% static "js\linechart.js" %}></script>
<script>
...

Related

Flask Plotly Responsive in Browser

How to make this plotly chart responsive in index.html - I create a flask app and js function for rendering the plot, however, I cannot figure out, how to make it responsive. What is wrong with variable config - it seems not to work.
Thank you
Flask:
#app.route('/')
def index():
locations = sorted(df['location'].unique())
rooms = sorted(df['rooms'].unique())
# Visualisation
import json
import plotly
import plotly.express as px
df.rooms = df.rooms.astype(str)
fig = px.scatter(df, x="m2", y="price", trendline="ols", color="rooms", symbol='rooms',
marginal_x="histogram",
marginal_y="rug",
template='plotly_dark', hover_data=['price', 'rooms', 'm2', 'location'],
title="Real Estate in Vienna")
graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)
return render_template('index.html', locations=locations, rooms=rooms, graphJSON=graphJSON)
JavaScript:
<!-- Visualisation -->
{%block content%}
<div class="card mb-4 m-auto" style="width: 90%">
<div class="card-body">
<div id="chart"></div>
</div>
</div>
{% endblock %}
<!-- Plotly -->
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script type="text/javascript">
var graphs = {{ graphJSON | safe}};
var config = {responsive: true};
Plotly.newPlot("chart", graphs, {}, config);
</script>
I think you are using Plotly.newPlot() wrong. By reading the API reference you will see, that there are to different signatures for this function:
Plotly.newPlot(graphDiv, data, layout, config)
Plotly.newPlot(graphDiv, obj)
Looks you were mixing both up since the Python function
graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)
returns a single object with keys for data, layout, config and frames with defaults to {data: [], layout: {}, config: {}, frames: []}.
Thus everything should work if you use the following JavaScript that extracts the parameters data and layout from the object charts and then use
Plotly.newPlot(graphDiv, data, layout, config)
instead of
Plotly.newPlot(graphDiv, obj):
<!-- Plotly -->
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script type="text/javascript">
var chart = {{graphJSON | safe}};
var data = chart["data"];
var layout = chart["layout"];
var config = {responsive: true};
Plotly.newPlot("chart", data, layout, config);
</script>

I'm facing a TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement

Hi I'm trying to create a horizontal bar chart using flask and facing the following error. TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement. Please help. Thanks in advance.
app.py
from flask import Flask, redirect, url_for, render_template, request, flash, session
import pandas as pd
app = Flask(name)
app.debug = True
#app.route('/', methods=['GET','POST'])
def index():
return render_template('index.html')
#app.route('/data', methods=['GET','POST'])
def dropdown():
if request.method == 'POST':
file = request.form['upload-file']
data = pd.read_excel(file)
data = pd.DataFrame(data)
colours=data['Question'].unique().tolist()
return render_template('test.html', colours=colours)
#app.route("/data/submitted", methods=['GET', 'POST'])
def charts():
#select = request.form.get('colour')
if request.method == 'POST':
to_filter = request.form.get['colours']
# filter the data here
plot_data = data[data['Themes'].str.contains(to_filter)]
plot_data['flag'] = 1
plot_data2 = plot_data.groupby(['Themes'])['flag'].sum().reset_index()
#colours1 = data1['Question'].unique().tolist()
labels = plot_data2['Themes'].tolist()
values = plot_data2['flag'].tolist()
bar_labels = labels
bar_values = values
return render_template("sample_chart1.html", labels=bar_labels,data=bar_values)
if __name__ == "__main__":
app.run(debug=True)
sample_chart1.html
<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>
<head>
<meta charset="utf-8" />
<title>Charts.js</title>
<!-- import plugin script -->
</head>
<h1>Chart</h1>
<!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div>
<!-- bar chart canvas element -->
<canvas id="chart" width="300" height="200"></canvas>
<p id="caption">Distribution of Topics.</p>
<script>
// create the chart using the chart canvas
var chartData = {
labels : [{% for item in labels %}
"{{item}}",
{% endfor %}],
datasets : [{
data : [{% for item in values %}
{{item}},
{% endfor %}],
spanGaps: false
}]
}
// get chart canvas
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
type: 'horizontal bar',
data: chartData,
});
</script>
It is making a GET request, which does not pass the if request.method == 'POST'
And since it does not pass there is no return for requests that aren't POST

getting the status of arduino digital pins in webpage

I want to read the status of my digital pins of arduino and want to display it
in web page. For web programming i am using Flask. I tried this code but its not working. from arduino side I am reading the values of 6 digital pins in the form of 1 and 0. How i can do this? Any help would be appreciated.
<!doctype html>
<html>
<head>
</head>
<body>
<h1 style="font-size:30px;font-family:verdana;"><b>STATUS READ </h1><br><br>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<p id="#status1"></p>
<p id="#status2"></p>
<p id="#status3"></p>
<p id="#status4"></p>
<p id="#status5"></p>
<p id="#status6"></p>
<script type=text/javascript>
function updatevalues() {
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
$.getJSON($SCRIPT_ROOT+"/a",
function(data) {
$("#status1").text(data.m+" %")
$("#status2").text(data.n+" %")
$("#status3").text(data.o+" %")
$("#status4").text(data.p+" %")
$("#status5").text(data.q+" %")
$("#status6").text(data.r+" %")
});
}
</script>
</body>
</html>
Python code:
from flask import Flask, render_template,request,redirect, url_for,jsonify,flash
import flask
from shelljob import proc
import math
import eventlet
eventlet.monkey_patch()
from flask import Response
import serial
import time
from datetime import datetime
import json
import random
from flask.ext.bootstrap import Bootstrap
from flask_bootstrap import WebCDN
app = flask.Flask(__name__)
app.secret_key = 'some_secret'
bootstrap = Bootstrap(app)
app.extensions['bootstrap']['cdns']['jquery'] = WebCDN('//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/')
arduino= serial.Serial( '/dev/ttyACM0' , 9600) #creating object
#app.route('/')
def home():
return render_template('status.html')
#app.route('/a',methods=['GET'])
def a():
mydata=arduino.readline().split(',')
return jsonify(m=float(mydata[0]),n=float(mydata[1]),o=float(mydata[2]),p=float(mydata[3]),q=float(mydata[4]),r=float(mydata[5]))
if __name__ == "__main__":
app.run()
It seems like you're not calling updatevalues in Javascript. You should try with something like this:
setInterval(updatevalues, 1000); //So it runs the function every 1000ms (1 second)

Save JavaScript GeoLocation data to Django admin page [duplicate]

Is it possible to save the javascript html5 geolocation latitude and longitude to the django admin when user uses the geolocation website. The web page goal is to save the user's longitude and latitude values so that the data can be accessed later on when user signs in again.
I found a similar question being asked in stackoverflow years ago but there hasn't been any answer. The link is : Save JavaScript GeoLocation data to Django admin page
It would be great if there this an answer based on this code link.
Another option I read about is to create a html form and set the form to be autopopulated by jQuery from data produced by the javascript html5 geolocation. Again this is quite complicated for a beginner like me.
I would appreciate any bit of help whether by code, tutorial, blog post, examples or links. I don't expect all the programming code to be provided (although I do learn better from examples) but it would help if there are some material/example I could go to, to implement my programming tasks. Thank you.
I am currently up to here with my progress but still am unable to post the latitude and longitude to the django admin page:
code is as following:
The structure of the django project is as follows:
-ajax
- __pycache__
- migrations
- __pycache__
0001_initial.py
__init__.py
- static
- css
- bootstrap.css
- fonts
- js
- script.js
- templates
- ajax
- base.html
- index.html
- __init__.py
- admin.py
- apps.py
- models.py
- tests.py
- urls.py
- views.py
-server
- __pycache__
- __init__.py
- settings.py
- urls.py
- views.py
- wsgi.py
-db.sqlite3
-manage.py
index.html
{% extends 'ajax/base.html' %}
{% block body %}
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Get Your Location</button>
<p id="demo"></p>
<button type="button" id="btn_submit" class="btn btn-primary form-control" disabled>Submit</button>
{% endblock %}
script.js
var pos;
var $demo;
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
$demo.text("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
pos = position;
var { latitude, longitude } = pos.coords;
$demo.html(`Latitude: ${latitude}<br>Longitude: ${longitude}`);
$('#btn_submit').attr("disabled", null);
}
$(document).ready(function() {
$demo = $("#demo");
$('#btn_submit').on('click', function() {
var data = pos.coords;
data.csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val();
$.post("/ajax/", data, function() {
alert("Saved Data!");
});
});
});
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1">
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'ajax/css/bootstrap.css' %}"/>
</head>
<body>
{% csrf_token %}
<nav class="navbar navbar-default">
<div class="container-fluid">
</div>
</nav>
<div class="col-md-3"></div>
<div class="col-md-6 well">
<h3 class="text-primary">Python - Django Simple Submit Form With Ajax</h3>
<hr style="border-top:1px dotted #000;"/>
{% block body %}
{% endblock %}
</div>
</body>
<script src = "{% static 'ajax/js/jquery-3.2.1.js' %}"></script>
<script src = "{% static 'ajax/js/script.js' %}"></script>
</html>
models.py
from django.db import models
# Create your models here.
class Member(models.Model):
latitude = models.DecimalField(max_digits=19, decimal_places=16)
longitude = models.DecimalField(max_digits=19, decimal_places=16)
views.py (ajax)
from django.shortcuts import render, redirect
from .models import Member
def index(request):
return render(request, 'ajax/index.html')
def insert(request):
member = Member(latitude=request.POST['latitude'], longitude=request.POST['longitude'])
member.save()
return redirect('/')
urls.py (ajax)
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name="index"),
url(r'^insert$', views.insert, name="insert")
]
views.py (server)
from django.shortcuts import redirect
def index_redirect(request):
return redirect('/ajax/')
urls.py (server)
from django.conf.urls import url, include
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^$', views.index_redirect, name="index_redirect"),
url(r'^ajax/', include("ajax.urls")),
url(r'^admin/', admin.site.urls),
]
It "POST"s the data but it does not appear in the django admin. I trawled many websites searching for answers why but still haven't found any. Thank you again for your help.
I have used jQuery and Ajax to submit the longitude and latitude data to any model you want to store these data in.
in your model.py:
from django.contrib.auth import User
class UserGeoLocation(models.Model):
user = models.OneToOneField(User)
latitude = models.FloatField(blank=False, null=False)
longitude = models.FloatField(blank=False, null=False)
for your view.py
def save_user_geolocation(request):
if request.method == 'POST':
latitude = request.POST['lat']
longitude = request.POST['long']
UserGeoLocation.create(
user = request.user
latitude= latitude,
longitude = longitude,
)
return HttpResponse('')
now that we have the view we can setup a url endpoint to submit the post request
url('^abc/xyz/$', appname.views.save_user_geolocation)
and Finally for the actual form,
$(document).on('submit', '#id', function(e){
e.preventDefault();
$.ajax(
type='POST',
url = 'abc/xyz',
data : {
lat:position.coords.latitude,
long: position.coords.longitude
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
});
for the last step, lets say you used the js code from the example you linked, then you can assign these coordinates value to variables that will be submitted with the post request that gets triggered when the user clicks on the button, the id here is the id of the form you want to submit the data from, and the e.PreventDefault is to stop the page from reloading when you post the data. Finally, the csrf token is required by django to able to submit the form.

Embedding multiple pieces of JavaScript via a Tornado UIModule

I'm working on a Python package that uses Tornado to send data to the browser for visualization. In order to do this, I want the users to be able to write multiple arbitrary modules for the server to render together on a single page -- including each module's own JavaScript.
However, by default, the Tornado's UIModule class's embedded_javascript() method only appends JavaScript to <script>...</script> once per module class. I'm hoping there is a simple way to embed multiple pieces of JS, one for every UIModule (or another way to get the same effect).
Here's a minimal example of what I'm talking about:
import tornado.ioloop
import tornado.web
import tornado.template
class Element(tornado.web.UIModule):
'''
Module to add some custom JavaScript to the page.
'''
def render(self, element):
self.js_code = element.js_code
return ""
def embedded_javascript(self):
return self.js_code
class InterfaceElement(object):
'''
Object to store some custom JavaScript code.
'''
def __init__(self, js_code):
'''
Args:
js_code: Some JavaScript code in string form to add to the page.
'''
self.js_code = js_code
class MainPageHandler(tornado.web.RequestHandler):
def get(self):
elements = self.application.modules
self.render("uitest_template.html", app_name="Testing", elements=elements)
class ThisApp(tornado.web.Application):
def __init__(self, modules):
self.modules = modules
main_handler = (r'/', MainPageHandler)
#settings = {"ui_modules": {"Element": Element}}
settings = {"ui_modules": {"Element": Element},
"template_path": "ui_templates"}
super().__init__([main_handler], **settings)
# Create two objects with some custom JavaScript to render
module_1 = InterfaceElement("var a = 1;")
module_2 = InterfaceElement("var b = 2;")
app = ThisApp([module_1, module_2])
app.listen(8888)
tornado.ioloop.IOLoop.instance().start()
And the template for uitest_template.html is just
<!DOCTYPE html>
<head>
<title> Hello World </title>
</head>
<body>
{% for element in elements %}
{%module Element(element) %}
{% end %}
</body>
The rendered page then includes a <script> tag in body that is:
<script type="text/javascript">
//<![CDATA[
var b = 2;
//]]>
</script>
And what I want is:
<script type="text/javascript">
//<![CDATA[
var a = 1;
var b = 2;
//]]>
</script>
Or something like it. Any ideas?
Added - my solution
Based on the answer below, here's how I ended up handling it:
import tornado.ioloop
import tornado.web
import tornado.template
class InterfaceElement(object):
include_js = [] # List of .js files to include
js_code = '' # JavaScript string to include
def __init__(self, include_js=[], js_code=''):
self.include_js = include_js
self.js_code = js_code
class MainPageHandler(tornado.web.RequestHandler):
def get(self):
self.render("modular_template.html",
includes=self.application.include_js,
scripts=self.application.js_code)
class ThisApp(tornado.web.Application):
def __init__(self, modules):
# Extract the relevant info from modules:
self.modules = modules
self.include_js = set()
self.js_code = []
for module in self.modules:
for include_file in module.include_js:
self.include_js.add(include_file)
if module.js_code != '':
self.js_code.append(module.js_code)
main_handler = (r'/', MainPageHandler)
settings = {"template_path": "ui_templates",
"static_path": "ui_templates"}
super().__init__([main_handler], **settings)
module_1 = InterfaceElement(js_code="var a = 1;")
module_2 = InterfaceElement(include_js=["test.js"], js_code="var b = 1;")
app = ThisApp([module_1, module_2])
app.listen(8888)
tornado.ioloop.IOLoop.instance().start()
Which goes with the following template:
<!DOCTYPE html>
<head>
<title> Hello world </title>
</head>
<body>
<!-- Script includes go here -->
{% for file_name in includes %}
<script src="/static/{{ file_name }}" type="text/javascript"></script>
{% end %}
<script type="text/javascript">
// Actual script snippets go here.
{% for script in scripts %}
{% raw script %}
{% end %}
</script>
</body>
embedded_javascript and related methods are (effectively) class-level methods; they must return the same value for any instance of the class. (They're intended to be a kind of dependency-management system, so you can load a piece of javascript only on pages that include a module that needs it)
The only thing that is allowed to vary per instance is the output of render(), so to embed multiple pieces of javascript you should include the script tag in the result of your render() method.

Categories

Resources