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?
Related
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.")
I created a function to create multiple PDFs with Weasyprint, zip them together and download the zip file. When trying to extract the folder on Windows 10 with the in-house zip program i get this error:
"An unexpected error is keeping you from copying the file. [...] Error 0x80070057" <
I can skip the error and the files get extracted. However in the best case scenario I'd like to prevent this error.
def get_all_shareholder_reports(request):
current_shareholders = list(models.objects.all())
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, "a") as zip_file:
for shareholder in current_shareholders:
pdf_file_handle = io.BytesIO()
context_dict = get_report_details(pk=shareholder.shareholder_id)
html_string = render_to_string('template.html',
context_dict)
html_handler = HTML(string=html_string, base_url=request.build_absolute_uri())
html_handler.write_pdf(target=pdf_file_handle)
pdf_file_handle.seek(0)
pdf_string = pdf_file_handle.getvalue()
pdf_file_name ='Shareholder_Report_{}_{}_{}.pdf'.format(context_dict['shareholder'].forename,
context_dict['shareholder'].surname,
datetime.datetime.now().strftime(
"%d_%m_%Y_%H:%M:%S"))
zip_file.writestr(zinfo_or_arcname=pdf_file_name, data=pdf_string)
zip_buffer.seek(0)
response = HttpResponse(zip_buffer.getvalue(), content_type="application/x-zip-compressed")
response['Content-Disposition'] = 'attachment; filename=%s' % 'myzip.zip'
return response
I figured it out: The zip file didn't like the ":" in the filename. Removing them fixed the issue.
pdf_file_name ='Shareholder_Report_{}_{}_{}.pdf'.format(context_dict['shareholder'].forename,
context_dict['shareholder'].surname,
datetime.datetime.now().strftime(
"%d_%m_%Y_%H_%M_%S"))
You basically need to clean the filename for all reserved characters in Windows: https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions
So the following should do it "filename".replaceAll("[<>:\"/\\\\|?*]", "")
I have a Django app in which when I click on the link then I can download a .txt file. Now instead of downloading that file I need to open that file (in 'r' mode). I'm trying to do something similar to that of mail attachments that is when we click on the attachment then it opens up instead of downloading. How can I do it ? The following code is to download the .txt file :
def fetch_logfile(request,logfile):
try:
folder,log,_ = logfile.split("/")
pathRelative = r"/LogFile/"+log
folder,log,_ = logfile.split("/")
pathRelative = r"/LogFile/"+log
path = pathRelative[1::]
os.startfile(pathRelative,open)
file_path =os.getcwd()+ '/' +pathRelative
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
nameOnly = log.split('/')
response['Content-Disposition'] = 'attachment; filename=%s' % nameOnly[len(nameOnly)-1]
return response
except:
## do something else
The following code works which I have tried in Python IDLE but when I try the same in Django then it doesn't work. I'm not sure if this is the right way either.Please advice me on this.
def fetch_Logfile(request,logfile):
import os,sys
path = "C:\\Users\\welcome\\Desktop\\mysite\\LogFile\\"+"756849.txt"
os.startfile(path,open)
## do something with logfile and request
def fetch_Logfile(request,logfile):
path = "C:\\Users\\welcome\\Desktop\\mysite\\LogFile\\"+"756849.txt"
import webbrowser
webbrowser.open(path)
## do something with logfile and request
def fetch_Logfile(request,logfile):
import win32api,os,subprocess
path = "C:\\Users\\welcome\\Desktop\\mysite\\LogFile\\"+"756849.txt"
filename_short = win32api.GetShortPathName(path)
subprocess.Popen('start ' + filename_short, shell=True )
subprocess.Popen('start ' + path, shell=True )
## do something with logfile and request
my_file = open(file_path, 'r')
response = HttpResponse(my_file.read(), mimetype='text/plain')
response['Content-Disposition'] = 'inline;filename=some_file.txt'
return response
Here is the MIME Types – Complete List
You can provide mimetype = ' / ' based on the file extension by referencing the mime type list.
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
i have implemented csv in my current Python Django project.
writer = csv.writer(open('custom_data/abc.csv', 'w+'))
print "abc"
headers = []
for i in data_desc:
headers.append((i[0].replace('_', ' ')).upper())
j = j+1
j=1
writer.writerow(headers)
"""
fill data into csv cells
"""
for value in data.fetchall():
k=0
no_record_check=1
row = []
for val in value:
row.append(val)
k = k+1
j=j+1
writer.writerow(row)
except:
print "Exception here after printing"
#pass
response = HttpResponse(mimetype='text/csv')
now = datetime.datetime.now().strftime('%m-%d-%Y_%H:%M:%S')
response['Content-Disposition'] = 'attachment; filename= custom_data/abc.csv'
code is working fine. and file with name abc.csv created successfully . but download option come with wrong name .
i have created file with name : abc.csv under custom_report and custom_report folder reside in my project folder. (e.g. projectname/custom_report/abc.csv). i found file under this location. ::
my project structure are:
projectname / app / app_name/ forms.py, views.py...
projetname / custom_report /abc.csv
** my issue issue :**
file come with new name custom_data_abc.csv. with blank data. while abc.csv file under the custom_report is availabe with correct data.
can you help me ?
Try this:
Sorry for the wrong reply .The tutorial says that:
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=unruly.csv'
writer = csv.writer(response)
First create a response and then write the content