在我的 django 模板的头部,我目前有:
<script>
$.get('get_students/', function (dict) {
alert(dict)
})
</script>
这提醒我一个对应于 dict 的 json 字典,它来自以下 django View :
def get_students(request):
students = Student.objects.all()
students_json = serializers.serialize('json', students)
return HttpResponse(json.dumps(students_json), content_type='application/json')
是否有可能将 dict 从脚本标签“转义”到普通的 Django 模板中,以便我可以用类似的东西迭代它:
{% for d in dict%}
<p>d.username</p>
{% endfor %}
如果有更明智的做法请推荐给我,我还在学习中。请注意,我在必须调用 View 的组件内部工作,这就是我使用 js get 的原因。
谢谢!
最佳答案
虽然它没有直接回答问题,但不能通过使用 get_context 将数据传递到 View 中来完成吗?方法而不是循环遍历它?
所以你的 View 看起来像这样:
class ExampleDetailView(DetailView):
model = Student
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
# Add in a QuerySet of all the books
context['contextDictionary'] = get_students()
return context
然后在模板中有类似的东西:
{% for d in contextDictionary %}
<p>d.username</p>
{% endfor %}
关于javascript - 如何将 json 字典从 javascript.get 传递到 django 模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58209619/