Forums

How to link to a downloadable PDF/DOC file?

I have a page where I want to link to a downloadable PDF file in my static assets here

> home > my_username > my_app > static >  files

I am passing it in to my page template thusly:

            <a href="{{ the_pdf_url }}" target="_blank" class="btn btn-primary">Download The PDF</a>

and in urls I have

from django.conf.urls import patterns, include, url


urlpatterns = patterns('',
url(r'^$','portfolio.views.home_page'),
url(r'^contact/$','portfolio.views.contact'),
url(r'^cv/$','portfolio.views.cv_page'),
url(r'^(?P<the_portfolio_type>\D+)/$','portfolio.views.portfolio_page'),
url(r'^(?P<portfolio_id>\d+)/$','portfolio.views.item'),
url(r'^cv/pdfs/(?P<filename>)/$', 'portfolio.views.pdf_download'),
)

and in views I have the following cribbed code, which I confess I don't understand 100% as to its function

def pdf_download(request, filename):
path = os.expanduser('~/portfolio/static/pdfs/')
f = open(path+filename, "r")
response = HttpResponse(FileWrapper(f), content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=resume.pdf'
f.close()
return response

When I click on the link it leads me to a blank page.

I get that I'm supposed to let Django know that this is a particular type of response, a PDF file particularly, but I'm a bit at a loss what I'm doing — and in the view code, it looks as if the filename is hardcode, whereas in url.py it seem I should be passing it in as a variable.

Any help appreciated!

I think the blank page is exactly what you should expect. Did you notice whether your browser started a download in the background? If I'm not mistaken and I'm reading the code correctly, that's the behaviour you're specifying.

The filename in the Content-Disposition line is, I believe, and instruction to the browser about what filename to use when it saves the PDF. You could, of course, use string interpolation to make it the same as the filename that was passed into the view.

Is there a reason you're not using the static files feature of PythonAnywhere?

Thanks, but it's not downloading.

How would I use the static files feature of PA in this context?

I have the static files directory set to

/static/    /home/robertanthony/portfolio/static

in the PA web section. I also have

STATIC_URL = '/static/'

STATIC_ROOT = '/home/robertanthony/portfolio/static/'

in my settings.py.

Is this overkill? I'm a bit confused, as a newbie

If you have that setup, you should be able to just get the pdf at http://robertanthony.pythonanywhere.com/static/pdfs/<whatever the PDF is called>.pdf

I have the same problem, How do I dowload the PFD files to my local folder?, Always pythonAnywhere give me the /home/...etc. gabrielaraya2011@gmail.com

Start with our documentation for static files: http://help.pythonanywhere.com/pages/StaticFiles/ and http://help.pythonanywhere.com/pages/DebuggingStaticFiles/