I have been told it is 'bad practice' to return data from a Django view and use those returned items in Javascript that is loaded on the page.
For example: if I was writing an app that needed some extra data to load/display a javascript based graph, I was told it's wrong to pass that data directly into the javascript on the page from a template variable passed from the Django view.
My first thought:
- Just get the data the graph needs in the django view and return it in a context variable to be used in the template. Then just reference that context variable directly in the javascript in the template.
It should load the data fine - but I was told that is the wrong way.
So how is it best achieved?
My second thought:
- Spin up Django Rest Framework and create an endpoint where you pass any required data to and make an AJAX request when the page loads - then load the data and do the JS stuff needed.
This works, except for one thing, how do I get the variables required for the AJAX request into the AJAX request itself?
I'd have to get them either from the context (which is the 'wrong way') or get the parameters from the URL. Is there any easy way to parse the data out of the URL in JS? It seems like a pain in the neck just to get around not utilizing the view for the data needed and accessing those variables directly in the JS.
So, is it really 'bad practice' to pass data from the Django view and use it directly in the Javascript?
Are both methods acceptable?
What is the Django appropriate way to get data like that into the Javascript on a given page/template?