【问题标题】:How to download a file from FileField django如何从 FileField django 下载文件
【发布时间】:2020-02-16 22:11:30
【问题描述】:

我正在构建一个应允许用户使用 Django 上传和下载文件的应用程序。

我有一个存储文件的模型:

class Document(models.Model):
    description = models.CharField(max_length=255, blank=True)
    unit_code = models.CharField(max_length=6)
    input = models.FileField(upload_to='documents/')
    uploaded_at = models.DateTimeField(auto_now_add=True)
    @property
    def filename(self):
        return os.path.basename(self.document.name)

我可以从我的视图中显示我的模板中上传的文件列表:

def Document(request, str):
    documents = Document.objects.filter(unit_code=str)

并在模板中使用here所见的url下载文件的锚标记:

{% for document in documents %}
    {{document.filename}}<a  href="{{document.input.url}}"> Download Document </a>
{% endfor %}

现在我收到一个错误找不到页面(网址指向127.0.0.1:8000/media/documents/file_name

是否可以通过 Django 开发服务器使用锚标签下载文件?

【问题讨论】:

    标签: django django-templates django-views


    【解决方案1】:

    假设您正确设置了 MEDIA_ROOT 和 MEDIA_URL 设置,您需要在 urls.py 中添加类似的内容

    from django.conf import settings
    from django.conf.urls.static import static
    
    urlpatterns = [
        # ... the rest of your URLconf goes here ...
    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    

    您可以阅读docs here

    重要:此解决方案仅在开发过程中有效。对于生产,您的媒体文件应该直接从 nginx(或您使用的任何 Web 服务器)而不是通过 Django 提供

    【讨论】:

    • 非常感谢。也感谢生产与开发技巧;我知道在生产过程中提供文件时要更加小心。
    猜你喜欢
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    • 1970-01-01
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多