在Django中加载媒体文件

2024-04-29 15:09:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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目录中,但这会破坏我项目的目的


Tags: pathdjango代码模板sourcetitlehtmlvideo
1条回答
网友
1楼 · 发布于 2024-04-29 15:09:20

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

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

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

即使您使用此url来呈现视频,它也无法用于任何其他网络设备,除非给定下面的文件系统路径,django的媒体服务器正在为该文件提供服务

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

django static file serving guide

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

相关问题 更多 >