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:
  • FileResponse efficiently streams files from storage.
  • Use as_attachment=True and filename=... for download.
  • Category Views (FBV & CBV)
  • Total Views 325
  • Last Modified 29 December, 2025
  • Tags #fileresponse #files #download #views
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.