FileResponse for Downloading Files
Return files with correct headers for download.
# models.py
from django.db import models
class Document(models.Model):
file = models.FileField(upload_to="docs/")
# admin.py
from django.contrib import admin
from .models import Document
@admin.register(Document)
class DocumentAdmin(admin.ModelAdmin):
list_display = ("file",)
# views.py
from django.http import FileResponse
from .models import Document
def download(request, pk):
doc = Document.objects.get(pk=pk)
return FileResponse(doc.file.open("rb"), as_attachment=True, filename=doc.file.name)
# urls.py
path("docs/<int:pk>/download/", download, name="download-document")
Explanation:
-
FileResponseefficiently streams files from storage. -
Use
as_attachment=Trueandfilename=...for download.
- Category Views (FBV & CBV)
- Total Views 325
- Last Modified 29 December, 2025
- Tags #fileresponse #files #download #views
Previous snippet
StreamingHttpResponse for Large Data
Next snippet