6

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.

Community
  • 1
  • 1
rnk
  • 2,174
  • 4
  • 35
  • 57

2 Answers2

9

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
Nader Alexan
  • 2,127
  • 22
  • 36
5

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.)

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Now the error is cleared. But the file is not yet downloadable. It just opens in the browser. – rnk Aug 06 '12 at 14:37