Django Send File To Download !!top!! May 2026
Do not use with open(...) inside your view when returning a FileResponse . Django needs the file to stay open so it can stream it after the view function finishes; it will close the file automatically once the download is complete. Django FileResponse - How to speed up file download
For very large files in production, use a web server like Nginx with the X-Accel-Redirect header instead of Django to serve the file directly. django send file to download
import io from django.http import FileResponse def download_report(request): buffer = io.BytesIO() # Logic to write data into the buffer (e.g., using Pandas or CSV writer) buffer.write(b"Name, Score\nJohn, 95\nJane, 98") buffer.seek(0) # Move to the start of the buffer return FileResponse(buffer, as_attachment=True, filename="report.csv") Use code with caution. 4. Legacy Method: HttpResponse Do not use with open(
For files created on the fly (like an Excel report or CSV), use a memory buffer such as io.BytesIO . import io from django
If you are using an older version of Django or need absolute control over headers, you can use HttpResponse .
To effectively, you should use the FileResponse class. This is the modern, recommended way to handle file downloads because it automatically sets the correct headers and streams the file in chunks to save memory. 1. The Standard Method: FileResponse
The most straightforward way to force a browser to download a file rather than just displaying it (like a PDF or image) is to use FileResponse with the as_attachment=True parameter.