Django downloading a file that had been uploaded before - python

I'm using Django 1.10 and I have a button on my home page that you can click to download a file (PDF or MP4). I have a ajax call going to my views.py
`def downloadfile(request):
if request.POST:
fileviewing = get_object_or_404(FileViewing, pk=request.POST.get("id"))
file_name = fileviewing.file.file.name
file_path = fileviewing.file.file.path
file_wrapper = FileWrapper(file(file_path,'rb'))
file_mimetype = mimetypes.guess_type(file_path)
response = HttpResponse(file_wrapper, content_type=file_mimetype)
response['X-Sendfile'] = file_path
response['Content-Length'] = os.stat(file_path).st_size
response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name)
return response`
This is my function to download a file but nothing happens when it goes through the fuction. There are no errors and the function runs completely but nothing is being downloaded.

Related

Unable to download file in django

I'm new to django and I have developed a django website which allows people to download epub file by typing the book's name. I have checked the django api about download and the code seems to work fine (no error reported), but there is no download window pops up by my browser. I'm testing on 127.0.0.1:8000 and here is part of my code
view.py
def download(request, file_path, book_name):
if os.path.exists(file_path):
response = HttpResponse(content_type="application/epub+zip")
response['X-Sendfile'] = file_path
response['Content-Disposition'] = 'attachment; filename=abc.epub'
print (response)
return response
raise False
According to my console it could find the file path, and by printing the message it shows
<HttpResponse status_code=200, "application/epub+zip">
[26/Mar/2018 18:31:03] "POST / HTTP/1.1" 200 509
Everything seems to work fine, just the download window does not pop up. Does anyone have any idea where is goes wrong? Thanks!
==========
Supplementary:
To give you a full sight of the view file, download is called by index and thats all:
def index(request):
template = loader.get_template('index.html')
book_name = ''
result = ''
if request.method == "POST": # check if user actually type a book name
book_name = request.POST.get("book_name")
cwd = os.getcwd()
if book_name != '': # search and create are functions from other file which would create an epub file and put it in current directory
result = search.search_ask(book_name)
create.create(book_name)
file_path = os.path.join(cwd, book_name) + '.epub'
download(request, file_path, book_name)
context = {'return_value': book_name,
'result_1': result,
'cwd': cwd}
return HttpResponse(template.render(context, request))
you don't return the response object returned by the download method. most be:
return donwload(request, file_path, book_name)
or
download_response = donwload(request, file_path, book_name)
if download_response:
return download_response
else:
# not found or other return.
in your code always return
return HttpResponse(template.render(context, request))

Could not save the csv file into folder using Django and Python

I am trying to save some .csv files into folder using Python and Django but it's throwing the below error.
Error:
Exception Type: NameError
Exception Value:
global name 'filename' is not defined
I am providing my code below.
report = Reactor.objects.all()
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename='+str(uuid.uuid4())+'.csv'
writer = csv.writer(response)
writer.writerow(['Name', 'Status', 'Date'])
for rec in report:
if rec.status == 1:
status = 'Start'
if rec.status == 0:
status = 'Stop'
if rec.status == 2:
status = 'Suspend'
writer.writerow([rec.rname, status, rec.date])
open(settings.FILE_PATH+filename,'w')
return response
settings.py:
FILE_PATH = os.path.join(BASE_DIR, '/upload/')
Here I wring the DB value into .CSV file and downloading it. In the same time I need to save that downloaded file into upload folder but getting those error.
It's exactly what the error is telling you. You haven't defined filename anywhere, but are calling it in open(settings.FILE_PATH+filename,'w')
Try:
filename = str(uuid.uuid4()) + '.csv'
response['Content-Disposition'] = 'attachment; filename=' + filename
Related, but not the problem that you're seeing, what's the point of opening the file for writing, but never writing anything to it?

Not able to see converted Excel to HTML through Django

I have converted on Excel(with 2 tabs) to HTML. Now I want to display this generated HTML on a webpage with Django code. But I am not able to get the entire data in my webpage.
Following is my Django code.
#api_view(['GET'])
def download_y9cfile1(request, file_name):
filePath = CommonUtils.get_absolute_file_path('app','static','generated','HTML', file_name)
logger.debug("File name is %s" % filePath )
try:
relevantFile = open(filePath,'rb')
response = HttpResponse((relevantFile), content_type='text/html')
response['Content-Disposition'] = 'inline; filename="%s"' %file_name
except IOError:
logger.exception("File doesn't exist")
return HttpResponse("File doesn't exist", status=500)
return response
I think the issue is that Django is not able to read the supporting CSS file for HTML.
Try passing the file contents to HttpResponse instead of the file handle:
response = HttpResponse(relevantFile.read(), content_type='text/html')

Downloading file from FileField in Django with a HTTP link in a HTML file

I create a link that when a user press it, it will download a pdf file from the media folder in Django to the users machine.
I tried different methods but all were wrong for me. It tells me that the file can not be found, or the code is running but the file is corrupted.
My Html link:
<td> Download</td>
My url pattern links into a view:
url(r'^download/$', views.DownloadPdf),
My FileField is like this:
upload_pdf = models.FileField()
Following snippet code is the view that downloads a corrupted pdf:
def DownloadPdf(request):
filename = '/home/USER/PycharmProjects/MyProject/media/Invoice_Template.pdf'
response = HttpResponse(content_type='application/pdf')
fileformat = "pdf"
response['Content-Disposition'] = 'attachment;
filename=thisismypdf'.format(fileformat)
return response
So, what I have to do to make it working ?
with open(os.path.join(settings.MEDIA_ROOT, 'Invoice_Template.pdf'), 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/pdf")
response['Content-Disposition'] = 'attachment; filename=invoice.pdf'
return response
#Sergey Gornostaev 's code just work perfect, but i post below my code because it is a aproach in a differect way.
I correct a little bit my code:
def DownloadPdf(request):
path_to_file = '/home/USER/PycharmProjects/MyProject/media /Invoice_Template.pdf'
f = open(path_to_file, 'r')
myfile = File(f)
response = HttpResponse(myfile, content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=filename'
return response
But only in pdf file ( works with txt files ) gives me that error:
'utf-8' codec can't decode byte 0xe2 in position 10

Django define name of file to serve

I have wrote a code which let user to download a file. This is the code :
def download_file(request, ref):
filepath = "/home/jedema/code_"+ref+".txt"
filename = os.path.basename(filepath)
final_filename = "code.txt"
return serve(request, filename, os.path.dirname(filepath))
I want to define the file name that user will download. At the moment, the name of downloaded file is the URL after my domain name.
Do you know how to define the name of file downloaded by user ?
You need to set the Content-Dispositionheader in your response. First of all you shouldn't use the serve() view, to deliver the file, because it only works as long as DEBUG = True is set.
With a look at the Django Docs something like the following should do the trick
def download_file(request, ref):
filepath = "/home/jedema/code_"+ref+".txt"
filename = os.path.basename(filepath)
final_filename = "code.txt"
with open(filepath) as f:
response = HttpResponse(f.read(), content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename="%s"' % final_filename
return response
I haven't tested it but it should be a hint into the right direction

Categories

Resources