Marvin
Marvin

Reputation: 243

How to pass Django data to an external JS file?

I am working on a Django project. I would like to pass a data from Django's views.py into a javascript file, run the js function then render the return value into my html page. I am not using a form in this project. Can someone please guide me on how to approach this? Most answers I see here are currently outdated and I've tried different approaches with no luck. I am using Python v2.7. Thank you in advance!

Upvotes: 2

Views: 6684

Answers (3)

Minhduong243
Minhduong243

Reputation: 93

I'd recommend json_script

Here is an example. My code in the views.py

def countymap(request):
    json_data = open('home/static/GEOJSON/NECounties2.geojson')
    countyData = json.load(json_data)
    return render(request, 'home/Countymap.html',
                  {'countyData': countyData})

On my HTML, I use json_script to get the data and assign an id to it. In addition, there is a separate Javascript file (let's call it Countymap)

<html>
blah blah blah
{{ countyData | json_script:"county-data" }}
<script type="text/javascript" src='{% static "js/Countymap.js" %}'></script>
<html>

Inside the Countymap javascript, use this to get the data

var countyData = JSON.parse(document.getElementById('county-data').textContent);

Hope it still helps

Upvotes: 0

Roy Prins
Roy Prins

Reputation: 3080

It might a good idea to directly render the javascript data inside a <script> tag on the template for the page. If it is to be used in several pages, make sure to include it in the base template or import it using a include.

Your view might resemble a standard django view:

def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404("Poll does not exist")
    return render(request, 'polls/detail.html', {'poll': p})

The template would have some added logic to build the javascript object:

<script>
var questionset = {
    {% for q in poll.question_set %}
        q.id : {
            "title": "{{ q.title }}",
            "score": {{ q.score }}
        }
        {% if not loop.last %},{% endif %}
    {% endfor %}
}
</script>

You now have a javascript object at your disposal in the template, that gets dynamically built from the data. You can use it as you please:

<script>
    function doSomething(questionset){
        ...
    }
</script>

There are ways to save your data to a javascript file, but bear in mind that this get cached by the client's browser. Not a good idea to have dynamic data in that.

Upvotes: 1

John McCabe
John McCabe

Reputation: 712

If your project is using Jinja or some other templating engine you could try passing the data into the template.

Found this bit on Writing your first Django app, part 3 and tweaked it a bit.

def index(request):
    template = loader.get_template('app/index.html')
    my_data = ['whatever your data is']
    context = {
        'my_data': my_data,
    }
    return HttpResponse(template.render(context, request))

And in index.html

<html>
    <head>
        // import jQuery
    </head>
    <body>
        <div id='my_data_label'></div>
        <script type="text/javascript">
            var my_data = "{{ my_data }}"; // gets set by jinja
            $('.my_data_label').text(my_data);
            // do whatever with the data
        </script>
    </body>
</html>

Not sure if this is exactly what you're looking for, but hope it helps.

Upvotes: 1

Related Questions