【问题标题】:Django render json response htmlDjango 渲染 json 响应 html
【发布时间】:2021-02-17 15:00:09
【问题描述】:

我正在尝试呈现一个 json 响应,该响应在我将参数发送到端点 url 后在正文中返回一个 html 页面,但我没有找到任何有关如何在 django 中处理此问题的信息。到目前为止,我能够在使用 JsonResponse(response.text,safe=False) 创建的空模板中看到 html,但它显示了带有标签和所有内容的 html。我愿意接受建议。注意:json 帖子会将所有参数发送到端点,作为响应,我会得到一个 html 页面,我需要向用户显示付款处理。

    headers = {'content-type': 'application/json'}
    url = 'https://paymentway.net/api.php'
    params ={
        "ClientId": "",
        "FirstName": fname,
        "LastName": lname,
        "Email": email,
        "Amount": amount,
        "InvoiceNumber": InvoiceNum 
    }
    

    response = requests.post(url, headers=headers, data= json.dumps(params))

【问题讨论】:

    标签: python django django-rest-framework django-templates


    【解决方案1】:

    检查render_to_string()

    from django.http import JsonResponse
    from django.template.loader import render_to_string
    
    ...
    
      def post(self, request, *args, **kwargs):
        ...
        return JsonResponse({
          'html': render_to_string('templates/form.html', context, request=request),
          ...
        })
    

    【讨论】:

    • 这里的问题是上下文需要是一个字典,而我的 json 响应是纯 html 代码
    • @kennethLebron 如果您需要纯 html,为什么要发送 json 响应?
    • 我设法使用 return HttpResponse(response.text)
    • 我正在发送带有一些参数的 Json Post,作为回报,我得到了传递了这些参数的纯 html 代码。
    • @kennethLebron 是的,那么你应该做 HttpResponse,而不是 JsonResponse,虽然我学会了总是提前考虑用 json 响应,因为有一天你需要传递状态、消息或其他任何东西你可能会遇到问题;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 1970-01-01
    • 2021-06-28
    • 2020-07-31
    • 2017-04-09
    • 2019-01-23
    相关资源
    最近更新 更多