Alexander Carter
Alexander Carter

Reputation: 25

How to import data from django.models, to use in javascript?

I am trying to import a python dictionary from moodels and manipulate/print it's properties in Javascript. However nothing seems to print out and I don't receive any error warnings.

Views.py

from chesssite.models import Chess_board
import json

def chess(request):
    board = Chess_board()
    data = json.dumps(board.rep)
    return render(request, 'home.html', {'board': data})

Here board.rep is a python dictionary {"0a":0, "0b":0, "0c":"K0"} - basically a chess board

home.html

<html>
   <body>
      {% block content %}
         <script>
            for (x in {{board}}) {
               document.write(x)
            }
         </script>
      {% endblock %}
   </body>
</html>

I also would very much appreciate some debugging tips! Thanks in advance, Alex

Upvotes: 1

Views: 278

Answers (2)

Tim Tisdall
Tim Tisdall

Reputation: 10392

Django defaults to escaping things as HTML, and that will make " into @quot;. Try changing {{board}} into {{board|safe}} to prevent the html escaping. Alternatively, in the view you can wrap the string in mark_safe() which is in django.utils.safestring to indicate that the string shouldn't be escaped.

Upvotes: 1

Nafees Anwar
Nafees Anwar

Reputation: 6608

To transfer data between django and javascript, dump data in django view and load in a javascript variable. Try to avoid django interpolation with javascript language constructs. It is unsafe, error prone, and can cause complexities. in view

data = json.dumps(board.rep)

in template

const data = JSON.parse('{{ data|safe }}')
// use normal javascript here. 'data' is a javascript array

for (let x of data) {
    document.write(x)
}

Upvotes: 1

Related Questions