首页 > 解决方案 > Django 渲染 json 响应 html

问题描述

我正在尝试呈现一个 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))

标签: pythondjangodjango-rest-frameworkdjango-templates

解决方案


检查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),
      ...
    })

推荐阅读