【问题标题】:Django HttpResponse in JsonResponseJsonResponse 中的 Django HttpResponse
【发布时间】:2020-06-28 14:45:37
【问题描述】:

在我的 django 项目中,为了避免另一个请求,我想返回一个带有 HttpResponse 的 JsonResponse,如下所示:

JsonResponse({"known": True, "space": render(request, 'space.html')}, status=200)

Django进程返回正常内部错误Object of type HttpResponse is not JSON serializable

我尝试了所有的网络解决方案(序列化器等),但找不到一种方法来返回带有字典条目的 json 格式(我的 javascript 所必需的),其中一个是我可以使用的整个 html 页面$("body").html(response["space"])

我错过了什么吗?

感谢您的宝贵时间。

【问题讨论】:

    标签: python django serialization httpresponse jsonresponse


    【解决方案1】:

    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)
    })

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-12
      • 2019-12-05
      • 2018-10-06
      • 1970-01-01
      • 2016-04-20
      • 2019-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多