【发布时间】:2019-10-09 10:57:36
【问题描述】:
我正在尝试下载上传到我的 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)
文件.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 来处理下载?如果是这样,我该怎么做。
【问题讨论】:
标签: django django-media