如何在Django中将两个带有html的变量作为JSON发送?

Ami*_*irM 3 python django json

我想呈现两个不同的 HTML 示例并将其作为对 ajax 请求的响应发送回来。

在我看来,我有这样的事情:

def getClasses(request):
   User = request.user 
   aircomcode = request.POST.get('aircompany_choice', False)

   working_row = Pr_Aircompany.objects.get(user=User, aircomcode=aircomcode)
   economy_classes = working_row.economy_class
   business_classes = working_row.business_class

   economy = render_to_response('dbmanager/classes.html', {"classes": economy_classes}, content_type="text/html")
   business = render_to_response('dbmanager/classes.html', {"classes": business_classes}, content_type="text/html")

   return JsonResponse({"economy": economy, 
                    "business": business})
Run Code Online (Sandbox Code Playgroud)

有了这个,我得到了错误:

0x7f501dc56588 处的 django.http.response.HttpResponse 对象不是 JSON 可序列化的”

我怎样才能完成我的任务?

在 js 中,当我收到响应时,我想将接收到的 HTML 插入到 corespoding 块中。像这样:

$.ajax({ # ajax-sending user's data to get user's classes
    url: url,
    type: 'post',
    data: {"aircompany_choice": aircompany_choice}, # send selected aircompanies for which to retrieving classes required
    headers: {"X-CSRFToken":csrftoken}, # prevent CSRF attack
}).done (result) ->
    add_booking_classes.find(".economy-classes").children(":nth-child(2)").html(result["economy"])
    add_booking_classes.find(".business-classes").children(":nth-child(2)").html(result["business"])
Run Code Online (Sandbox Code Playgroud)

Rah*_*pta 6

试试 Django 的render_to_string

economy = render_to_string('dbmanager/classes.html', {"classes": economy_classes})
business = render_to_string('dbmanager/classes.html', {"classes": business_classes})
Run Code Online (Sandbox Code Playgroud)

render_to_string()加载一个模板,渲染它,然后返回结果字符串。然后,您可以将这些结果字符串作为 JSON 发送。

您的最终代码现在变为:

from django.template.loader import render_to_string

def getClasses(request):
   User = request.user 
   aircomcode = request.POST.get('aircompany_choice', False)

   working_row = Pr_Aircompany.objects.get(user=User, aircomcode=aircomcode)
   economy_classes = working_row.economy_class
   business_classes = working_row.business_class

   economy = render_to_string('dbmanager/classes.html', {"classes": economy_classes})
   business = render_to_string('dbmanager/classes.html', {"classes": business_classes})

   return JsonResponse({"economy": economy, 
                    "business": business})
Run Code Online (Sandbox Code Playgroud)