首页 > 解决方案 > 我们可以在 python 字典中发送 django `render()` 的 HttpResponse 吗?

问题描述

我的用例是我需要将整个 render() 数据放入一个字典中,该字典也将具有其他键值,最后我可以将它作为正常响应返回。

假设我的代码是:

from django.shortcuts import render

def my_view(request):
    # View code here...
    return render(request, 'myapp/index.html', {
        'foo': 'bar',
    }, content_type='application/xhtml+xml')

现在我们在这里做的是:render 基本上是返回一个我们正在返回的 HttpResponse。

我需要的是:

将返回响应保存在变量中

x = render(request, 'myapp/index.html', {
            'foo': 'bar',
        }, content_type='application/xhtml+xml')

那么我们可以将它保存在字典中以作为响应返回吗?像这样

y = {}
y = {name: 'testing', render_response: x}
return y

标签: pythondjangodjango-views

解决方案


你不能从视图返回一个普通的字典,它应该返回一个HttpResponse对象。您可以从您的视图中返回JsonResponse 。就像评论中提到的@Daniel 一样,使用render_to_string以字符串格式获取响应。

from django.template.loader import render_to_string
from django.http import JsonResponse


def my_view(request):
    # View code here...
    response = render_to_string('myapp/index.html', {'foo': 'bar'}, request=request)
    context = {'name': 'testing', 'render_response': response}
    return JsonResponse(context)

推荐阅读