【问题标题】:Download Html file instead of render in Django下载 Html 文件而不是在 Django 中渲染
【发布时间】:2022-10-13 15:37:11
【问题描述】:
所以我几乎是一个 django 新手,我什至不知道我所问的是否可能;-;
所以基本上我正在做的是一个用户可以传递上下文的网站
然后 django 用上下文填充模板
但是,我不想渲染模板,而是让模板填充了可供下载的上下文
我希望能够下载 index.html
我知道浏览器具有保存网页功能,但在移动设备上 javascript 不起作用,我从 Google 图标获得的图标也无法加载
【问题讨论】:
标签:
python
django
django-templates
【解决方案1】:
这很容易,您的视图以类似的结尾
return render(request,"index.html",context)
应该改成这样
from io import StringIO
from django.http import FileReponse
response = render(request,"index.html",context)
f = io.StringIO(response.content)
return FileResponse(f, as_attachment = True, filename = "index.html")
【解决方案2】:
应该改成这样
from io import StringIO
from django.http import FileResponse
response = render(request,"index.html",context)
file = StringIO(response. Content)
return FileResponse(file, as_attachment = True, filename = "index.html")
或者,如果您使用这样的 XML 模板,您可以像这样使用它:
from io import BytesIO
from django.http import FileResponse
response = render(request,"index.html",context)
file = BytesIO(response. Content)
return FileResponse(file, as_attachment = True, filename = "index.xml")