Django:让 render_to_response 接受磁盘上的字节而不是 html

Django: Getting render_to_response to accept bytes rather than html on disk

我有一个即时生成的 html 文件,我不想将其保存到磁盘。通常在 Django 中,要向用户获取 html,您可以使用:

return render_to_response('foo.html', context_instance=RequestContext(request))

但是,我的磁盘上没有 foo.html,我有一个 bytes 字符串。如何让 Django 呈现字符串而不是文件? (注意:生成的文件有{% block content %}等Django需要解释的

使用 python3.4 和 Django 1.8.

在 cyphase 的建议下: 我做了以下事情:

my_template = Template(byte_string)
return HttpResponse(my_template.render(RequestContext(request)))

试试这个:

from django.http import HttpResponse
from django.template import Template

def your_view(...):
    # Do stuff

    yourtemplate = Template(your_template_string)

    content = yourtemplate.render(context_instance=RequestContext(request))

    # content_type and status are the same as would be passed
    # to render() or render_to_response().
    return HttpResponse(content, content_type=None, status=None)

理想情况下,有人会实现一个 render_to_response() 接受字符串或类似文件的对象。