Download Html file instead of render in Django

Issue

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

Solution

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

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published