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
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.
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.
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.
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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With