使用Django在模板视图中访问python dic

时间:2019-06-03 05:26:08

标签: javascript django django-templates django-views

当我要将dic从views.py传递到模板时,它无法正确呈现。

我尝试使用| safe和JSON.parse(),但是都不能解决问题。似乎该错误可能已经在views.py中发生了。


views.py

participant_per_challenge = {}

for participant in challenge_participants:

        if str(participant.challenge.id) in participant_per_challenge:
            participant_per_challenge[str(participant.challenge.id)].append(participant.player.userid)
        else:
            participant_per_challenge[str(participant.challenge.id)] = []
            participant_per_challenge[str(participant.challenge.id)].append(participant.player.userid)


my_dict = {
 'challenges' : challenges,
 'challenge_participants' : challenge_participants,
 'unique_participants': unique_participants,
 'participant_per_challenge': participant_per_challenge,

 }

return render(request, "challengeview/index.html", context=my_dict)

此处是 views.py

中的示例dic
{
  "1": [
    "bc5ac2b77a2d4b9e90ff4aa6012a4891",
    "a61254636e5f432292459b406cf55f47"
  ],
  "2": [
    "a61254636e5f432292459b406cf55f47",
    "bc5ac2b77a2d4b9e90ff4aa6012a4891"
  ]
}


index.html

<script type="text/javascript">
var player_per_challenge = "{{ participant_per_challenge|safe}}";
console.log(typeof player_per_challenge); //THIS RETURNS STRING

</script>

预期结果:我可以访问其参数的JSON对象


  

实际结果:字符串。 JSON.parse()不能正常工作(“未捕获的SyntaxError:带有JSON.parse的意外令牌”)。

1 个答案:

答案 0 :(得分:0)

您应该在视图中将dict编码为JSON,并在Javascript代码中使用它(不带引号)。例如:

views.py

import json
...
'participant_per_challenge': json.dumps(participant_per_challenge),

然后

index.html

var player_per_challenge = {{ participant_per_challenge | safe}};