Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Downloaded File Name

I use a simple view class to "force download" a file by its pk. The file downloaded name comes out to be the pk. I would like it to be the original file name, like it is on the server. How do i do that?

*Im new to django

here the view's code

class GetFileContent(View):
def get(self,request, userName, pk):
    user = User.objects.filter(username = userName)
    filtered = File.objects.filter(pk = pk, published=True, file_owner = user)
    data = filtered[0].content
    return HttpResponse(data, content_type='application/force-download')
    pass
like image 712
Yoav Schwartz Avatar asked Sep 06 '25 02:09

Yoav Schwartz


1 Answers

You need to set the filename on the response:

response = HttpResponse(data, content_type='application/force-download')
response['Content-Disposition'] = f'attachment; filename={filename}' # F-strings are typically more readable and efficient compared to the str.format() method. However, if you're working with older Python versions, you may need to use str.format()
return response

You'll need to figure out a way to determine the desired filename (e..g, by storing it in the database as well for lookups).

like image 116
Simeon Visser Avatar answered Sep 07 '25 19:09

Simeon Visser