Hi I'm creating pdf file but I face an error [WinError 2] The system cannot find the file specified but I don't know where is the error
if os.path.exists(pdf_file_output):
with open(pdf_file_output, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/pdf")
response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(pdf_file_output)
return response
Your code is unable to locate the file specified (probably in Windows). There are few reasons:
Wrong file path: Check if that pdf_file_output file path is correct and the file is exist in that location.
Permission problem: Make sure that the current user has permissions to access the file.
Typo in the filename: Check if that there are no typos in the file name and the file name is the same as you're trying to access.
Alternative script that helps you to debug your code:
import os
pdf_file_output = ...
if os.path.exists(pdf_file_output):
with open(pdf_file_output, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/pdf")
response['Content-Disposition'] = 'attachment; filename=' +
os.path.basename(pdf_file_output)
return response
else:
print(f"The file '{pdf_file_output}' doesn't exist.")
Related
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?
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
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
This is code to download files but when file downloads and i open them :the archive is unknown and damaged. Can you please help me to solve this problem here code is:
def download(request):
file_name =request.GET.get('file_name', '')
the_file = "C:\\Users\\CV_Uploads\\uploadfiles\\uploadfiles\\uploaded_files\\1395901478_89_uploadfiles.rar"
filename = os.path.basename(the_file)
response = HttpResponse(FileWrapper(open(the_file)),
content_type=mimetypes.guess_type(the_file)[0])
response['Content-Length'] = os.path.getsize(the_file)
response['Content-Disposition'] = "attachment; filename=%s" % filename
return response
When you are dealing with paths you should use raw string .
use
the_file = r"C:\Users\CV_Uploads\uploadfiles\uploadfiles\uploaded_files\1395901478_89_uploadfiles.rar"
i am writing this function in views.py file:
def download(request):
file = open("D:\wamp\www\User_App.rar","r")
mimetype = mimetypes.guess_type("D:\wamp\www\User_App.rar")[0]
if not mimetype: mimetype = "application/octet-stream"
response = HttpResponse(file.read(), mimetype=mimetype)
response["Content-Disposition"]= "attachment; filename=%s" % os.path.split("D:\wamp\www\User_App.rar")[1]
return response
to download file but when that downloads and i open this it is damaged. how to solve this problem.
Open files in binary mode:
file = open(r"D:\wamp\www\User_App.rar", "rb")
as opening files in text mode means line endings are translated to a platform-neutral \n character.