TemplateView将一些上下文数据序列化为json

时间:2014-11-16 11:38:22

标签: json django serialization django-class-based-views

我发现了许多相关的问题,但没有运气=(

视图

from django.core import serializers

class LargeMapView(TemplateView):
    template_name = 'map/index.html'

    def get_context_data(self, **kwargs):
        context = super(LargeMapView, self).get_context_data(**kwargs)
        human_values = Human.objects.all()
        search_work_values = SearchWork.objects.all()

        # context['human_data'] = json.dumps(list(human_values))
        # context['search_work_data'] = json.dumps(list(search_work_values), cls=DjangoJSONEncoder)

        context['human_data'] = serializers.serialize('json', human_values)
        context['search_work_data'] = serializers.serialize('json', search_work_values)

    return context

模板

<script type="text/javascript">
       var lala = {{ human_data }};
</script>

结果我有Uncaught SyntaxError: Unexpected token &

 var lala = [{&quot;pk&quot;: 13, &quot;model&quot;: &quot;human.human&quot;, &quot;fields&quot;: {&quot;burial_type&quot;: null, &quot;last_name&quot;: &quot;&quot;, ...

1 个答案:

答案 0 :(得分:0)

好吧我似乎已经解决了

{{ human_data|safe }}

在视图中使用mark_safe

mark_safe(serializers.serialize('json', human_values, fields=('pk', 'fio', 'lat', 'lon')))