【发布时间】:2018-07-28 06:21:59
【问题描述】:
我正在尝试从我的 Django 应用程序的模板中下载静态文件。
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 %}
目前我的当前输出相当明显 - Django 正在寻找匹配的 url 模式,但它失败了。我在 download_file(request): 中的 filename="nowy.odf" 是硬编码 atm 仅用于测试目的。
我正在考虑的2个解决方案:
1) 在 url.py 中为 url 模式创建适当的正则表达式,以满足重定向到我无法完成的 download_file 视图 2)我应该以某种方式更改我的静态/pdf文件夹的显示方法
更新
我之前添加了 STATIC_URL 和 STATIC_ROOT 作为也运行 collectstatic (我的应用程序正在生成 pdf 并将它们保存到静态文件夹中,这是这样做的必要条件)。我还添加了 URL 模式部分(使用 serve,而不是 static_view.serve,因为文档是这样说的)。
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
不幸的是,我不了解静态前期的路径
<a href="{% static 'django-pdf/generator/static/pdfs/nowy.pdf' %}">{{ file }}</a>
更准确地说,这里的静态是如何工作的以及这意味着什么。当前输出仅显示未找到该文件。应用程序在调试模式 atm 下不起作用。
【问题讨论】:
标签: python django django-templates django-views