使用Django模板系统返回JSON响应

使用Django模板系统返回JSON响应,json,django,Json,Django,可能吗? 我试过: json.html文件: {% load i18n %} '{"date": "{{ date|escapejs }}", "test": "hello"}' 答复是: '\n\n{"date": "2014\u002D11\u002D13 11:58:31.635102", "test": "hello"}' 因此,错误是: SyntaxError: JSON.parse: unexpected character at line 3 column 1 of th

可能吗? 我试过:

json.html文件:

{% load i18n %}

'{"date": "{{ date|escapejs }}", "test": "hello"}' 
答复是:

'\n\n{"date": "2014\u002D11\u002D13 11:58:31.635102", "test": "hello"}' 
因此,错误是:

SyntaxError: JSON.parse: unexpected character at line 3 column 1 of the JSON data

您应该使用Django templatetags。您可以创建自己的或使用

在这种情况下,您可以在json.html文件中立即使用
templatetag

{% now "SHORT_DATETIME_FORMAT" %}

简单的方法是首先将模板中的数据呈现为字符串,并将其作为json响应,如下面的示例代码所示

from django.template.loader import render_to_string
from django.http import HttpResponse
def jsonview(request):
      context = {}
      context['data'] = render_to_string("json.html", {'date': datetime.now()})
      return HttpResponse(json.dumps(context), content_type="application/json")

为什么要这样做,而不是在视图中将其构建为字典,并使用
json.dumps()
?来利用django模板。不能转储datetime对象,但应首先复制django模板的功能。
from django.template.loader import render_to_string
from django.http import HttpResponse
def jsonview(request):
      context = {}
      context['data'] = render_to_string("json.html", {'date': datetime.now()})
      return HttpResponse(json.dumps(context), content_type="application/json")