I want to make a PDF file in my project directory to be downloable instead of opening in the browser when a user clicks the link.
I followed this question Generating file to download with Django
But I'm getting error:
Exception Type: SyntaxError
Exception Value: can't assign to literal (views.py, line 119)
Exception Location: /usr/local/lib/python2.7/dist-packages/django/utils/importlib.py in import_module, line 35
I created a download link:
<a href="/files/pdf/resume.pdf" target="_blank" class="btn btn-success btn-download" id="download" >Download PDF</a>
urls.py:
url(r'^files/pdf/(?P<filename>\{w{40})/$', 'github.views.pdf_download'),
views.py:
def pdf_download(request, filename):
path = os.expanduser('~/files/pdf/')
f = open(path+filename, "r")
response = HttpResponse(FileWrapper(f), content_type='application/pdf')
response = ['Content-Disposition'] = 'attachment; filename=resume.pdf'
f.close()
return response
The Error Line is:
response = ['Content-Disposition'] = 'attachment; filename=resume.pdf'
How can I make it downloable?
Thanks!
UPDATE
It is working in Firefox but not in Chrome v21.0.
You can download files from a URL using the requests module. Simply, get the URL using the get method of requests module and store the result into a variable “myfile” variable. Then you write the contents of the variable into a file.
To download a file with Curl, use the --output or -o command-line option. This option allows you to save the downloaded file to a local drive under the specified name. If you want the uploaded file to be saved under the same name as in the URL, use the --remote-name or -O command line option.
Use the following code and it should download the file instead of opening it in a new page
def pdf_download(request, filename):
path = os.expanduser('~/files/pdf/')
wrapper = FileWrapper(file(filename,'rb'))
response = HttpResponse(wrapper, content_type=mimetypes.guess_type(filename)[0])
response['Content-Length'] = os.path.getsize(filename)
response['Content-Disposition'] = "attachment; filename=" + filename
return response
You've got an extra =
in that line, which makes the syntax invalid. It should be
response['Content-Disposition'] = 'attachment; filename=resume.pdf'
(Note that having two =
doesn't necessarily make it invalid: foo = bar = 'hello'
is perfectly valid, but in that case both the left and the middle term are names. In your version, the middle term is a literal, which can't be assigned to.)
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