Greetings, I am currently facing an issue with passing a template variable to javascript in order to create a chart. Unfortunately, Django treats all js files as static files which means that dynamic template variables are not accessible within javascript.
I attempted the solution mentioned here:
passing template variables to javascript
However, it didn't resolve the issue as only one variable could be successfully passed while the others couldn't.
def profile(request,username):
try:
u = User.objects.get(username=username)
questions = Question.objects.filter(user=u)
answers = Answer.objects.filter(user=u)
docs = Document.objects.filter(user=u)
except User.DoesNotExist:
pass
return render(request,"auths/profile.html",locals())
In addition, my profile.html contains the following code as per the suggestion in the aforementioned link:
<input type="hidden" value="{{ u.username }}" id="username" />
<input type="hidden" value="{{ docs.count }}" id="docs" />
<input type="hidden" value="{{ questions.count }}" id="questions" />
<input type="hidden" value="{{ answers.count }}" id="answers" />
{% block extra %}
<script type="text/javascript">
var user = document.getElementById("username").value;
var docs = document.getElementById("docs").value;
var questions = document.getElementById("questions").value;
var answers = document.getElementById("answers").value;
</script>
<script type="text/javascript" src="{% static 'highcharts.js'%}"> </script>
<script type="text/javascript" src="{% static 'highcharts-3d.js'%}"></script>
<script type="text/javascript" src="{% static 'chart.js' %}"></script>
{% endblock %}
Furthermore, there is a snippet from my chart.js file where I assign the data to be displayed on the chart:
series: [{
type: 'column',
name: 'User Profile',
data: [
['Questions', questions],
['Answers', answers],
['Documents', docs]
]
}]
The challenge here remains that only one variable is being successfully passed while the remaining ones are not, resulting in the failure to render the desired chart. Any advice or suggestions from fellow developers would be greatly appreciated.
For reference, I am using Django 1.9 along with highcharts for this project.