18

I have a Django view which returns an HttpResponse with a special MIME type to make the user's browser "download" the file instead of view it in the browser. The problem is that the default filename that the response will be saved as is the URL which the user tried to access.

Is there any way to include a default filename in the HttpResponse object or do I have to redirect to a different URL to make this happen?

Deniz Dogan
  • 25,711
  • 35
  • 110
  • 162

1 Answers1

37

There's a relevant example in the docs:

from django.http import HttpResponse

def some_view(request):
    # Create the HttpResponse object with the appropriate headers.
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'
    return response
benjaoming
  • 2,135
  • 1
  • 21
  • 29
Dominic Rodger
  • 97,747
  • 36
  • 197
  • 212
  • 1
    Minor note: you need quotes around the filename or browsers will use "download.bin". That is: filename="somefilename.pdf" – vrplumber Sep 02 '14 at 21:09
  • 2
    Got an error trying to use mimetype, but changing the HttpResponse to HttpResponse(content, content_type='application/pdf') worked for me – Dfranc3373 Aug 15 '18 at 17:55