django在视图功能中获取媒体网址

时间:2014-10-15 09:49:01

标签: python django

在视图功能中提供媒体文件

View.py

file_path = Tracks.objects.get(pk=event_id)
name = file_path.file.name
fullpath = os.path.abspath(name)

当我执行上述功能时,完整路径会抛出错误:

[Errno 2] No such file or directory: '/home/ri/studio/videotube/uploads/2014/10/15/Wildlife_512kb_hVnnOc2.mp4'

但实际文件位于file:///home/ri/studio/videotube/videotube/site_media/media/uploads/2014/10/15/Wildlife_512kb_hVnnOc2.mp4

这是我的媒体根MEDIA_ROOT = os.path.join(PACKAGE_ROOT, "site_media", "media")

如何在视图功能中获取媒体网址?

1 个答案:

答案 0 :(得分:12)

您可以通过以下方式访问设置变量:

from django.conf import settings

your_media_root = settings.MEDIA_ROOT

但您也可以像获取名称一样访问文件路径:

name = file_path.file.name
url = file_path.file.url
path = file_path.file.path