Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Serving a Download File

I'm trying to serve a txt file generated with some content and i am having some issues. I'vecreated the temp files and written the content using NamedTemporaryFile and just set delete to false to debug however the downloaded file does not contain anything.

My guess is the response values are not pointed to the correct file, hense nothing is being downloaded, heres my code:

    f = NamedTemporaryFile()
    f.write(p.body)

    response = HttpResponse(FileWrapper(f), mimetype='application/force-download')
    response['Content-Disposition'] = 'attachment; filename=test-%s.txt' % p.uuid
    response['X-Sendfile'] = f.name
like image 281
Callum Avatar asked Apr 03 '13 14:04

Callum


People also ask

How do I use Django to serve files?

Serving static files during development If you use django.contrib.staticfiles as explained above, runserver will do this automatically when DEBUG is set to True . If you don't have django.contrib.staticfiles in INSTALLED_APPS , you can still manually serve static files using the django.views.static.serve() view.

How do I make my Django file downloadable?

In order to create a download link, we need to create a Django view that would serve the files: # views.py import mimetypes ... def download_file(request): # fill these variables with real values fl_path = '/file/path' filename = 'downloaded_file_name. extension' fl = open(fl_path, 'r') mime_type, _ = mimetypes.

What does Collectstatic do in Django?

collectstatic. Collects the static files into STATIC_ROOT . Duplicate file names are by default resolved in a similar way to how template resolution works: the file that is first found in one of the specified locations will be used. If you're confused, the findstatic command can help show you which files are found.

How can I download Excel file in Django?

Download data as Excel file in Django: It is always recommended to user virtual environment. Once virtual environment is activated, Run this command to add xlwt package. Inside your view, import xlwt package. Use below code in your view in views.py file to create and download excel file.


2 Answers

Have you considered just sending p.body through the response like this:

response = HttpResponse(mimetype='text/plain')
response['Content-Disposition'] = 'attachment; filename="%s.txt"' % p.uuid
response.write(p.body)
like image 81
Ric Avatar answered Oct 20 '22 04:10

Ric


XSend requires the path to the file in response['X-Sendfile'] So, you can do

response['X-Sendfile'] = smart_str(path_to_file)

Here, path_to_file is the full path to the file (not just the name of the file) Checkout this django-snippet

like image 40
karthikr Avatar answered Oct 20 '22 05:10

karthikr