python - Django - 手动构建 HttpResponse,但也想使用模板

标签 python django django-templates

当使用 render_to_response 返回一个 HttpResponse 对象时,您可以提供一个模板,它将使用该模板并填写所有 {{ variables }} 你已经在你的模板中设置了。

如果我想手动构建我的 HttpResponse 对象,是否仍可以在我的模板目录中使用我的模板之一?

最佳答案

使用 render_to_string ,您将获得呈现的字符串。您可以将返回的字符串传递给 HttpResponse

from django.template.loader import render_to_string

...

rendered = render_to_string('my_template.html', {'foo': 'bar'})
response = HttpResponse(rendered)

关于python - Django - 手动构建 HttpResponse,但也想使用模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22579708/

相关文章:

python - 如何使用特定用户拥有的对象创建 ModelForm

python - SK学习: TypeError: __init__() got an unexpected keyword argument n_splits

python - Django - 将文件名列表呈现给模板

python - 自定义 django 管理模板的单元测试

python - 将日期和时间戳格式的数据插入 PostgreSQL

python - 单个项目中的 django/python 的多个版本

python - 为什么在 Set-Cookie header 字段中找不到 CSRF token ?

python - Django 将占位符添加到内置登录表单的 Django

Django 管理员不显示模型

django - 如何在 Django 中将 CharField 渲染为静态文本?