1

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

0

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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)
}

1 Comment

You can do just const data = {{ data|safe }}. There's not much point in wrapping it into a string and then parsing it again. Also, you'll need an |escapejs instead of |safe to make sure quotes are properly escaped within a JS string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.