1 year ago
#70883

Scott Skiles
How to render Django context data (JSON) within external JavaScript file?
The question I have is:
How do I get template-ed JSON data to be usable by .js
file to see and use JSON data from my Django context?
The problem I am trying to solve is:
I am working on adding a CSP (Content Security Policy) to my Django website. The catch is that I have some inline JavaScript when templating JSON variables. This wouldn't be a problem, but the templating is inside the JavaScript section of the .html
file. Thus, in order to abide by a strict CSP, I need to move the entire JavaScript portion out of the .html
file and into a .js
file. The code I need to move looks like this:
<script>
let data = [
{
"key" : "Last 10 Days",
"values" : {{ last_ten_days }},
},
{
"key" : "Daily Score",
"bar": true,
"values" : {{ daily_scores }},
}
].map(function(series) {
series.values = series.values.map(function(d) { return {x: d[0], y: d[1] } });
return series;
});
</script>
I am passing the values via a Django TemplateView to the context so I can render the data to plot, using NVD3.js, on my webpage. It looks something like this:
class TheScores(LoginRequiredMixin, TemplateView):
template_name = 'the_scores.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
...
context['last_ten_days'] = last_ten_days
context['daily_scores'] = daily_scores
return context
So when move this section of JavaScript out of my HTML template the variable templating of the JSON data for last_ten_days and daily_scores no longer works.
I do not know how to get the JavaScript to see the data without leaving it inline, which would violate the strictness required for the CSP to be of any worth (seems like an all or none thing). So the resultant move creates an external JS file that is the same as above, call it scores.js
:
Problem Here: scores.js
has no idea how to load last_ten_days
or daily_scores
as JSON:
let data = [
{
"key" : "Last 10 Days",
"values" : {{ last_ten_days }},
},
{
"key" : "Daily Score",
"bar": true,
"values" : {{ daily_scores }},
}
].map(function(series) {
series.values = series.values.map(function(d) { return {x: d[0], y: d[1] } });
return series;
});
Then, when I replace the inline section of JavaScript with <script src="{% static "js/scores.js" %}" ></script>
the JavaScript does not read the {{
}}
as Django variable templating (rightly so). And so the question is, how can I use JSON data via a Django template within JavaScript while implementing strict CSP? Thanks.
javascript
json
django
content-security-policy
0 Answers
Your Answer