2

I'm currently learning both django and javascript

I passed a json string from python to javascript and this is the string i got.

[{"model": "polls.question", "pk": 1, "fields": {"question_text": "anything", "pub_date": "2017-09-07T09:36:07Z"}}, {"model": "polls.question", "pk": 2, "fields": {"question_text": "hi", "pub_date": "2017-09-07T10:01:39Z"}}]

whenever I use the JSON.parse method my javascript crashes

javascript:

let mylist = "{{ question_list_as_json | escapejs }}";
let temp = JSON.parse(mylist);

python:

question_list = Question.objects.all()
question_list_as_json = serializers.serialize('json', question_list)
return render(request, 'polls/index.html', {'question_list': question_list, 'question_list_as_json': question_list_as_json})

1 Answer 1

2

in your context question_list but in the template question_list_as_json, try it:

    question_list = Question.objects.all()
    question_list_as_json = serializers.serialize('json', question_list)
    context = {
        'question_list': question_list,
        'question_list_as_json': question_list_as_json
    }
    return render(request, 'polls/index.html', context)
Sign up to request clarification or add additional context in comments.

6 Comments

sorry i didn't copy the code correctly the json string does pass correctly to javascript but my problem is that i'm unable to pars it
try single quotes mylist = '{{ question_list_as_json }}'; without jsescape
thanks for the help, i did found a syntax problem above the mentioned code i fixed it now when i pars the json i get the following [object Object],[object Object] how do i continue from here
sorry but this is for js expert, i don't sure with correct answer
no problem you were a great help, thank you, will now look for the method
|

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.