1

I am trying to make static files download-able from the template of my Django app.

def list(request):
    folder = '/home/galander/Desktop/Projekty/django-pdf-generator/django-pdf/generator/static/pdfs'

    file_list = os.listdir(folder)
    return render_to_response('list.html', {'file_list': file_list})


def download_file(request):
    pdf_folder = '/home/galander/Desktop/Projekty/django-pdf-generator/django-pdf/generator/static/pdfs'
    response = HttpResponse(pdf_folder, content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="nowy.pdf"'
    return response

list.html

{% for file in file_list %}
    <a href="/home/galander/Desktop/Projekty/django-pdf-generator/django-pdf/generator/static/pdfs/{{ file }}">{{ file }}</a>
{% endfor %}

My current output is rather obvious at the moment - Django is looking for matching url pattern and it fails. My filename="nowy.odf" in download_file(request): is hard-coded atm just for testing purposes.

2 Solutions I am thinking of:

1) Create appropriate regex for url pattern in url.py to satisfy redirection to my download_file view which i fail to accomplish 2) I should change the display method for my static/pdf folder somehow

update

I have previously add STATIC_URL and STATIC_ROOT as also run collectstatic ( my app is generating pdfs and saving them into static folder, that was required to do so). I've also added URL pattern part (with serve, not static_view.serve becuase docs say so).

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")

if settings.DEBUG:
urlpatterns += [
    url(
        r'^media/(?P<path>.*)$', serve,  # NOQA
        {'document_root': settings.MEDIA_ROOT,
        'show_indexes': True}
    ),
] + staticfiles_urlpatterns()  # NOQA

My Project looks like that: enter image description here

Unfortunately I don't understand the path with static upfront

    <a href="{% static 'django-pdf/generator/static/pdfs/nowy.pdf' %}">{{ file }}</a>

To be more accurate, how the static works here and what does that mean. Current output just shows that the file wasn't found. App doesn't work in debug mode atm.

markwalker_
  • 12,078
  • 7
  • 62
  • 99
michael93pl
  • 337
  • 1
  • 7
  • 17

2 Answers2

1

You need to make use of django's static files app.

Usually in your settings.py you'll define static paths something like;

STATIC_ROOT = os.path.join(BASE_DIR, 'static-collection')
STATIC_URL = '/static/' 

Then you run manage.py collectstatic which gathers all of your static files into your STATIC_ROOT directory which you have your project serve from your STATIC_URL.

In debug mode you can add the following to your urls.py;

urlpatterns = []

# This is only needed when using runserver.
if settings.DEBUG:
    urlpatterns += [
        url(
            r'^media/(?P<path>.*)$', static_views.serve,  # NOQA
            {'document_root': settings.MEDIA_ROOT,
            'show_indexes': True}
        ),
    ] + staticfiles_urlpatterns()  # NOQA

So, looking at what you've posted, your project is probably Projekty and one of your apps is django-pdf-generator. If you have a static directory in your apps, django will collect the static files in to your STATIC_ROOT during collectstatic. So maybe have a path like Projekty/django-pdf-generator/static/django-pdf/generator/pdfs

Based on that, in a template you might do;

<!DOCTYPE html>
{% load static from staticfiles %}

<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">

    <title>My website</title>

    <!-- ALL OF THE STYLES -->
    <link rel="stylesheet" href="{% static "css/style.css" %}">
</head>

<body>

    <p>Click <a href="{% static 'pdfs/nowy.pdf' %}">here</a> to download my PDF</p>


</body>

Hopefully you can see in the template there how the path matches up to the static path in your app?

markwalker_
  • 12,078
  • 7
  • 62
  • 99
  • When I hard-coded my url pattern to `url(r'^home/galander/Desktop/Projekty/django-pdf-generator/django-pdf/generator/static/pdfs/nowy.pdf/', views.download_file, name='download_file')` it's loading download_view.view and works perfectly however obviously it shouldn't be hard-coded. It seems that creating regex to url pattern matching the path of the file would work here. However, I am lacking with the idea how to make it dynamic – michael93pl Feb 17 '18 at 15:30
  • Ok, with your static settings like that I think django will complain that your static root & static URL are the same. Also, `{% static %}` is just django's static application's template tag for the inclusion of static files in templates. Based on your screenshot you could include the PDF files in your template like; `{% static 'pdfs/nowy.pdf' %}`. You said you're generating PDFs though. If you're creating content you shouldn't be storing it in static. Have a look for some tutorials or something; https://djangobook.com/generating-pdfs/ – markwalker_ Feb 17 '18 at 15:38
  • This still doesn't work. I am looking for proper regex to match my requirements atm. About saving files in static folder - I have a requirement to avoid keeping files in db. The only solution to store them was static folder actually but if You say so, I may need to find some other solution. Thanks anyway :) – michael93pl Feb 17 '18 at 15:59
  • You are actually right and it should be in media files, not static -_- – michael93pl Feb 17 '18 at 16:18
0

you can use simple html tag to download static files

{% load static %} <!-- In top-->

<a href="{% static "mysite/resume.docx" %}" alt="My image">Click Here</a>

and keep the file(e.g. resume.docx) inside myapp/static/mysite

static file path

Ruben Helsloot
  • 12,582
  • 6
  • 26
  • 49
Denil Nair
  • 86
  • 5