yoa*_*rch 1 python django serialization httpresponse jsonresponse
在我的 django 项目中,为了避免另一个请求,我想返回一个带有 HttpResponse 的 JsonResponse,如下所示:
JsonResponse({"known": True, "space": render(request, 'space.html')}, status=200)
Django进程返回正常的内部错误Object of type HttpResponse is not JSON serializable
我尝试了所有的网络解决方案(序列化器等),但找不到一种方法来返回带有字典条目的 json 格式(我的 javascript 必需的),其中一个是我可以与 then 一起使用的整个 html 页面$("body").html(response["space"])。
我错过了什么吗?
谢谢你的时间。
该render函数返回一个HttpResponse,事实上,json序列化器不知道如何处理它。
您可以使用render_to_string[Django-doc]将其渲染为字符串:
from django.template.loader import render_to_string
…
JsonResponse({
'known': True,
'space': render_to_string('space.html', request=request)
})Run Code Online (Sandbox Code Playgroud)