Can someone advise what is the cleanest/easyest way to connect my query to the Data/Label part of chart.js script?
Thank you in advance.
CodePudding user response:
For example, you can do this in your views.py
:
# inside views.py
from django.views.generic import View
from django.shortcuts import render
class YourView(View):
def get(self, request, *args, **kwargs):
context = {} # <- you can add whatever you want in here
# some code...
return render(request, "path/to/js/file", context, content_type="text/javascript")
Inside your urls.py
from django.urls import path, include
from . import views
urlpatterns = [
path("data/js", views.YourView.as_view(), name="somejs"),
# and other urls...
]
Inside your template (html file)
<!-- this is just an example -->
<div>
<canvas id="myChart"></canvas>
<script type="text/javascript" src="{% url 'somejs' %}"></script>
<div/>
Inside your js file, you can do some javascript.
var chart = document.getElementById("myChart");
"{{some_context}}" // you can access to the context
{% if some_context %}
// do something
{% endif %}