2

I need to get the data from my models as an object in Javascript. I use this in my JS code ("data" being part of the context returned in my Django view) :

var data= {{ data|safe }};

And in my view I have :

context = {'data': {
             'model1': serializers.serialize('json', model1.objects.all()),
             'model2': serializers.serialize('json', model2.objects.all()),
          }

The problems I have are :

1) I get an error in JS unless I use "safe" on the context variable,

2) Even if I use "safe", the object is unusable because it is just a string (i.e. data.model1[0] return "[" instead of the first element in the array).

What is the proper way of doing this ?

2 Answers 2

2

The trouble is that while the values of data are valid JSON, data itself is a Python dict which is not valid as JSON.

Probably the easiest way to do this would be to separate out the variables:

var data = {
    model1: {{ data.model1|safe }},
    model2: {{ data.model2|safe }}
}
Sign up to request clarification or add additional context in comments.

Comments

2

You could use the json module, a solution could be:

import json

data = {
        'model1': json.loads(serializers.serialize('json', model1.objects.all())),
        'model2': json.loads(serializers.serialize('json', model2.objects.all())),
       }
context = {'data': json.dumps(data)}

then var data = {{data|safe}}

Comments

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.