Passing values from Python to Javascript

381 views
Skip to first unread message

steve Valet

unread,
May 23, 2018, 7:52:05 AM5/23/18
to Django users
I am trying to pass values from Django/Python to Javascript, and have it working to a degree, but need some assistance (obligatory: I'm new to Django so could be hosing this)

I have three files in play here, views.py, app.js, home.html. I can get the values passed to home.html as part of the render, but I can't get the code to work outside of the home.html file. Below is a very simplified example of what I'm doing. 

VIEWS.PY
return render(request, "home.html", {'data':data'})

HOME.HTML

<html>

     <head>

          <script src="{% static '/js/app.js' %}"></script>

          <script>

               myFunction({{ data | safe }});

          </script>

     </head>

</html>


APP.JS

function myFunction(vars){
    return vars
};



I would like to have the JS in the HTML file in the APP.JS file so I can centralize all Javascript, but cannot get it to work outside the HTML. I also tried sending the "data" to JSON using "json.dumps" but got an error that the data was not serializable, so went with this code posted above.

Can I do what I'm trying to do?

Thanks
Steve

Akshay Gaur

unread,
May 23, 2018, 9:32:08 AM5/23/18
to Django users
Hi Steve,

I am new to Django as well. To do what you wanted to do (pass values from python to js), I used ajax queries (using jquery) and then did a JsonResponse to the ajax call. The ajax call then handles the data as required.

Sample usage:
VIEWS.PY:
class InstructorDeleteView(DeleteView):
model = Instructor
success_url = reverse_lazy('instructor_list')
template_name = 'class_management/instructor_list.html'

def delete(self, request, *args, **kwargs):
"""
Calls the delete() method on the fetched object and then
responds to the call with the relevant data.
"""
self.object = self.get_object()
pk = self.object.pk # Save the primary key before the object is deleted.
self.object.delete()
data = {
'message': "Successfully deleted the instructor.",
'pk': pk,
}
return JsonResponse(data)

Then, in you template, you can add js and have a ajax call to the view above so that it can receive the JsonResponse:

TEMPLATE:
$.ajax({
method: "POST",
url: $id + "/delete/",
data: $data,
success: handleSuccess,
error: handleError,
});

function handleSuccess(data, textStatus, jqXHR) {
console.log("SUCCESSFULLY DELETED INSTRUCTOR.");
console.log("Removing the deleted entry from the table.");
$('#row' + data['pk']).remove();
console.log(data);
console.log(textStatus);
console.log(jqXHR);
}

function handleError(jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown)
}

This was a POST request using AJAX and I am sure a GET request will work fine as well.

Please note: There might be better alternatives out there. I just don't know them yet :)

Best,
Akshay

Cuneyt Mertayak

unread,
May 23, 2018, 2:40:48 PM5/23/18
to Django users
As you can guess this is general problem for all backend languages for passing data to JS. 

AFAIK the standard practice is attaching the value to a DOM element as "data" property and using fetching the value from that element in your JS. If it is a primitive value it is easy to do so, if it is relatively complex structure, e.g. dictionary of classes etc. you can create a string representation of it (maybe in JSON format) and pass it to the template. Check out this link's method #4, it is on .NET but the idea is the same: https://blog.mariusschulz.com/2014/02/05/passing-net-server-side-data-to-javascript.

Hope it helps!
Message has been deleted

Akshay Gaur

unread,
May 24, 2018, 9:44:39 AM5/24/18
to Django users
Hi Cuneyt,
How do you add the data fields and their values to tags generated by python? For example, how would you add a data field to something generated by {{ form.name }}?

Cuneyt Mertayak

unread,
May 24, 2018, 2:56:54 PM5/24/18
to Django users
It is going to be like following.

In HTML (doesn't have to be div of course any HTML tag can get data attribute:
<div id="backend-to-js-name" data-name="{{form.name}}">...</div>

Then in JS:
var dataElement = document.getElementById('backend-to-js-name');
console.log(name);

Reply all
Reply to author
Forward
0 new messages