【问题标题】:Load Media Files in Django在 Django 中加载媒体文件
【发布时间】:2020-01-19 07:51:13
【问题描述】:

我正在尝试使用 Django 创建家庭媒体服务器。为此,我希望它的媒体文件存储在外部 USB 中。现在,当我尝试加载视频时,从我的代码中,它不起作用。我什至尝试对路径进行硬编码,看看它是否有效。当我通过 Django 运行时,它不起作用,但是当我直接在 chrome 中打开 HTML 时,它工作得很好。

占位符模板代码:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <video width="640" height="480" controls autoplay>
      <source src="E:/Programming\Projects\Youtube Downloader\Ariana Grande - One Last Time (Official).mp4" type="video/mp4">
    </video>
    <p><b>Note:</b> The autoplay attribute will not work on some mobile devices.</p>
  </body>
</html>

实际模板:

{% extends 'MediaPlayer/layout.html' %}

{% block MainContent %}
    {{ video_source}}
    <video width="640" height="360">
        <source src="E:/OneLastTime.mp4" type="video/mp4">
    </video>
    <p><b>Note:</b> The autoplay attribute will not work on some mobile devices.</p>
{% endblock %}

{% block PageScripts %}
{% endblock %}

调用模板的视图:

def select_video_page(request, video_id):
    file_path = FILE_SCANNER.files["video"][video_id]
    context = {
        "video_source": file_path,
        "title": '.'.join(file_path.split("\\")[-1].split(".")[:-1])
    }
    return render(request, "MediaPlayer/selectvideopage.html", context)

页面上的一切都运行良好,模板加载和一切。我面临的唯一问题是视频文件。我发现的几乎所有解决方案都需要将媒体存储在 Django 下的 media 目录中,但这会违背我的项目目的。

【问题讨论】:

    标签: python html django python-3.x


    【解决方案1】:

    如果您发布您的 settings.py,它将有助于确定您的问题。

    您正在尝试从您的 Django 项目中提供静态媒体。您需要正确指定要用作媒体根目录的目录,即 USB 驱动器。此外,我没有看到任何重要的方法可以使 django 应用程序支持 USB 驱动器的热插拔,如果媒体断开连接,这也可能导致其他问题。

    此 HTML 表明您没有从媒体服务器提供文件(除非您在 settings.py 中将 MEDIA_URL 定义为 E:)

    即使您使用此 url 来呈现视频,它也不适用于任何其他网络设备,除非该文件由 django 的媒体服务器提供,并给出以下文件系统路径。

    <source src="E:/OneLastTime.mp4" type="video/mp4"> 
    

    django static file serving guide

    您很可能需要使用 python 的 OS 模块导航到 USB 驱动器上的目录,然后将该目录声明为您的媒体根目录,以便 django 从中提供文件。可能存在阻止从项目根目录之外提供文件的内置安全功能。

    【讨论】:

    • 将 MEDIA_ROOT 设置为 E:/ 工作,谢谢。至于热插拔,我将在树莓派上运行它,所以我将有一个包装脚本来处理它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-20
    • 1970-01-01
    • 2012-04-12
    • 2018-12-09
    • 1970-01-01
    • 2021-03-29
    • 2018-12-23
    相关资源
    最近更新 更多