python - 我们可以在 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
解决方案
你不能从视图返回一个普通的字典,它应该返回一个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)
推荐阅读
- r - 尝试在 %dopar% 中使用函数 get() 两次时在 R 中出错
- python - Pydrake - 为植物添加旋转接头
- javascript - 使用变量值从 React 类的状态问题中检索对象值
- vue.js - 显示我添加到矩阵的食谱
- bash - 使用 head 和 tail 命令显示选定的行
- http - 服务器端出现意外错误时使用哪个 http 代码?
- python - 用张量流连接两个数据集
- jquery - 在 html 文件中引用 nuget 包
- sql-server - SQL 错误:将数值转换为数值的算术溢出错误 - 使用 Numeric(20,20) 列类型
- python - Python FTPS (FTP_TLS) 连接被拒绝。没有证书?