Download Html file instead of render in Django

Question:

So I am pretty much a django newbie, I do not even know if what I am asking is possible ;-;
So basically what I’m making is a website where users can pass context
Then django populates a template with the context
But instead of rendering the template I want to make the template populated with context available for download

I want to be able to download index.html

I know browsers have a save webpage feature but on mobile the javascript does not work and the icons i got from Google icons also do not load

Asked By: user16238776

||

Answers:

This is pretty easy, your view ends with something like

 return render(request,"index.html",context)

It should be changed to something like this

 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")
Answered By: Mohamed ElKalioby

It should be changed to something like this

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")

Or if you are using such XML templates you can use it like this:

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")
Answered By: Dhia Alshalabi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.