JSON data dumped in Django views is not modeled as expected in template javascript.

Asked 2 years ago, Updated 2 years ago, 425 views

I'm trying to write a graph using Django user data.
I have configured views to send the model in JSON format as follows:

views.py

diary_list=serializers.serialize('json', Diary.objects.filter(author=current_user.id).order_by('write_date')))

Diary.objects.filter(author=current_user.id).order_by('write_date')
defaultconverter(o):
        if isinstance(o, (datetime, date)) :
            returno.isoformat() + 'Z'

# dump data_to pass the data to Javascript
diary_listJSON=dumps(diary_list, sense_ascii=False, default=defaultconverter)

I received it by template as follows.

template

 {{diary_list|json_script:'diary_lists'}}}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js" type="text/javascript">/script>
<canvasid="myChart" height="450" width="700">/canvas>
<script type="text/javascript">

    // Prepare graph, data
    varctx= document.getElementById("myChart").getContext("2d");
    constdiarylist=JSON.parse( document.getElementById('diary_lists').textContent, function(key,value){
        if(key=="write_date"){
            return new Date (value);
        } else{
            return value;
        }
    });
    console.log(diarylist);
    console.log (typeof diarylist.pk);

The output of the first console.log is

"[{\"model\":\"diaries.diary\"',\"pk\":2,\"fields\":{\"author\":2,\"written_date\":\"2021-11-04\"',\"emotion_score\":550,\"title\":\"test post 2\"',\"content\":\"\".Building the backend is also difficult to configure initially, but the rest is much easier.\"}, {\"model\":\"diary.diary\"',\"pk\":1,\"fields\":{\"author\":2,\"write_date\":\"2021-11-21\"',\"emotion_score\":60,\"title\"\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\

I thought it was a good parse, but the result of the second console.log is

 undefined

So it doesn't seem to be a good object in javascript.
Please let me know how to make it a javascript model.

javascript json django

2022-09-30 22:00

1 Answers

If the object you are trying to reference is correct below, the reference method is different.

[{
  fields: {
    author —2,
    content: "Posted as Test 2.It's difficult to set up the backend at first, but the rest is much easier.",
    emotion_score:50,
    title: "Test Post 2",
    write_date: [object Date] {...}
  },
  model: "diaries.diary",
  pk:2
}, {
  fields: {
    author —2,
    content: "Building backend successfully",
    emotion_score —60,
    title: "Test Input",
    write_date: [object Date] {...}
  },
  model: "diaries.diary",
  pk:1
}]

Incorrect Reference Method

diarylist.pk

Correct reference method (I don't know which object you're trying to reference...)

diarylist[0].pk
diarylist[1].pk


2022-09-30 22:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.