如何生成文件下载链接?

时间:2019-04-26 09:12:48

标签: django python-3.x django-templates

我创建了一个不使用FileField()的模型,并将URL保存到路径字段中。现在,在显示时,我可以看到属性,但是无法下载文件。 href将该页面视为页面,并且出现错误消息GET请求失败。

我也需要对静态文件进行同样的操作。

models.py看起来像这样:

import os

from django.conf import settings
from django.db import models

# Create your models here.
class Document(models.Model):
    code = models.CharField(max_length = 50)
        path = models.CharField(max_length = 500)
    date_of_submission = models.CharField(max_length = 50)
    type = models.CharField(max_length = 50)
    title = models.CharField(max_length = 200)
    department = models.CharField(max_length = 50)
    subject = models.CharField(max_length = 100)
    updation_allowed = models.CharField(max_length = 1, default = '0')

    @property
    def relative_path(self):
        return os.path.relpath(self.path, settings.MEDIA_ROOT)

模板具有如下代码:

    <a href = '{{ MEDIA_URL }}{{ value.thesis.relative_path }}'> Thesis </a>

    *static files*
   <a href='/uploads/report.pdf'> Front Page</a>

我尝试使用该属性并自行提供路径。

2 个答案:

答案 0 :(得分:0)

urls.py(project / urls.py)

from django.conf.urls.static import static

urlpatterns = [
    ...
]

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

settings.py

...

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

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

答案 1 :(得分:0)

要允许文件下载,您需要创建一个单独的视图,并以FileResponse作为响应。该视图将采用html模板中提供的url的一些唯一参数(我想它将是文件的相对路径)。在此视图内,FileResponse将通过提供的路径打开文件,然后返回文件的响应。我认为您应该这样做:

  

Views.py:

def download_file(request, relative_path): # this is a view with file response
    media_root = settings.MEDIA_ROOT
    return FileResponse(open(f"{media_root}\{relative_path}", "rb"), as_attachment=True, filename="some_name.smth")
  

模板:

    <a href = '{% url "download" relative_path=value.thesis.relative_path %}'> Thesis </a>

    *static files*
   <a href='/uploads/report.pdf'> Front Page</a>
  

urls.py:

urlpatterns = [
    path("download-file/<slug:relative_path>/", views.download_file, name="download")]

您需要将其与PATH结合使用才能使其正常工作。