In my views.py file, I have the following dictionary:
data = {'pk': '1980.24', 'model': 'artworks.metaData', 'fields': {'medium': 'Oil on canvas ', 'description': 'missing', 'credit': 'Gift of Nicholas Wyeth, 1980 ', 'collection': 2, 'height': '21.7', 'culture': 'Missing value', 'depictedPeople': 'missing', 'creation_date': '1896 ', 'account': 'n/a', 'original_url': 'http://www.metmuseum.org/art/collection/search/10738?sortBy=Relevance&what=Canvas%7cOil+paintings&ao=on&ft=*&offset=0&rpp=100&pos=1', 'url': 'annotatie01.io.tudelft.nl/collections/Metropolitan/1980.24.jpg', 'title': 'Gooseberries ', 'object_number': '1980.24', 'width': '35.7', 'artist': 'Joseph Decker '}}
I wish to be able to use/access this dictionary on my webpage.
My attempts:
I tried to send data using the render in my views.py,
def foo():
context = {'data':data}
return render(request, 'index.html', context=context)
to access it using:
<script type="text/javascript">
var received_data = "{{data}}";
</script>
Using this, data is transmitted, but it's garbled:
"{'pk': '1980.24', 'model': 'artworks.metaData', 'fields': {'medium': 'Oil on canvas ', 'descripti...etc
I tried using json.dumps(data)
and JSON.parse(received_data )
but this raised an error:
Uncaught SyntaxError: Unexpected token & in JSON at position 1.
In short:
How can I send JSON data from Py to JS using Django Render()?
When we want to pass data from Django to JavaScript, we usually talk about APIs, serializers, JSON and AJAX calls. This is usually combined with the additional complexity of having a React or Angular running the frontend.
Django has a tag for disabling the auto-escaping it does though. This allows you to do the following: <script> </script> And voila! Django renders the JSON String in such a way that Javascript can work with it right away, without having to use JSON.parse on it.
This is useful if you need to send some data back to the user with HTML formatting inside your JSON after an AJAX request. The first step is to import the Django JsonResponse class and get_template function at the top of your view file like this:
We no-longer have JavaScript, but rather JavaScript, mixed with Django templates. We lose the opportunity to extract the JavaScript to a separate .js file. We also lose the opportunity to run prettier on that JavaScript. We can do it better & still be quick about it. n our view, serialize the data via json.dumps & store it in context.
simplest way will be
<script type="text/javascript">
var received_data = "{{ data|safe }}";
</script>
Security warning.
json.dumps
does not escape forward slashes: an attack is {'</script><script>alert(123);</script>': ''}
The trick is to convert your dict into a string for django 1.5+ do :
import json
def foo():
js_data = json.dumps(data)
render_template_to_response("imageView/index.html", {"data": js_data})
In imageView/index.html
keep:
<script type="text/javascript">
var received_data = "{{data|safe}}";
console.log(received_data);
</script>
Else do:
from django.utils import simplejson
def foo():
js_data = simplejson.dumps(data)
render_template_to_response("imageView/index.html", {"data": js_data})
In imageView/index.html
keep:
<script type="text/javascript">
var received_data = "{{data}}";
console.log(received_data);
</script>
You should pass the Django {{data}} to a raw JS String in order to prevent JS encoding/decoding problems.
<script type="text/javascript">
let received_data = String.raw`{{ data|safe }}`;
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With