您可以利用Django的模板加载器来渲染您的模板,包括您传递给它的任何上下文,作为字符串,然后将其保存到文件系统.如果您需要在外部系统(如Amazon S3)上保存该文件,则可以使用
Boto库.
以下是使用可选的querystring参数作为触发器将视图呈现到文件的示例.
from django.shortcuts import render
from django.template.loader import render_to_string
def my_view(request):
as_file = request.GET.get('as_file')
context = {'some_key': 'some_value'}
if as_file:
content = render_to_string('your-template.html', context)
with open('path/to/your-template-static.html', 'w') as static_file:
static_file.write(content)
return render('your-template.html', context)