Home > Software design >  Displaying D3.js Chart with Django Backend
Displaying D3.js Chart with Django Backend

Time:07-05

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 enter image description here

CodePudding user response:

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