如何在 Django 中从 user_directory_path 下载文件

How to download files from user_directory_path in django

我正在尝试下载已上传到我的 Django 媒体目录的文件。 我能够成功上传文件,但我不知道下载回这些文件的最佳方法。我在网上看到了不同的例子,但我并不完全理解它们。这是我的代码

models.py:

def user_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
    return 'user_{0}/{1}'.format(instance.user.id, filename)

class Profile(models.Model):
       user = models.OneToOneField(User, on_delete=models.CASCADE)
       certification = models.FileField(upload_to=user_directory_path, blank=True)

urls.py

    urlpatterns = [
    .........
    path('profile/', user_views.profile, name='profile'),

]

if settings.DEBUG:
   urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

file.html:

        <a href="{{ user.profile.certification.url }}">Download Certification</a>

我收到这个错误:

ValueError
     The 'certification' attribute has no file associated with it.

我是否在 views.py 中创建一个视图并在 urls.py 中创建一个 url 来处理下载?如果是这样,我该怎么做。

错误信息很清楚:

The 'certification' attribute has no file associated with it.

这意味着此 profile 实例的 certification 字段为空(未上传文件)。你不能在没有文件路径的情况下构建 url,对吗?

这里有两个解决方案:将 certification 字段设置为必填字段(删除 blank=True 参数)- 但如果您已经拥有没有认证的配置文件,这将无法解决问题 - 以及/ 或在尝试获取 url:

之前测试 profile.certification
{% if user.profile.certification %}
   <a href="{{ user.profile.certification.url }}">Download Certification</a>  
{% else %}
    <p>This user hasn't uploaded their certification</p>
{% endif %}