使用Django和html5标签播放视频 [英] Playing Video with Django and html5 tag
问题描述
我正在尝试通过将django与html5视频标签一起使用来播放视频,但不能。
主要问题是服务器无法获取视频
文件。
我收到此错误:
I am trying to play a video by using django with html5 video tag but couldn't.
The main problem is that the server cannot get a video
file.
I got this error:
[06/Jan/2014 23:52:07] "GET absolute_path_of_media/sample.mp4 HTTP/1.1" 404 2422
元素:
在这里,我将向您展示我的代码。
templates / videoplay.html:
Here, I will show you my code.
templates/videoplay.html:
{% extends "app/base.html" %}
{% block contents %}
<video name='demo' controls autoplay width='50%' height='40%'>
<source src="{{media}}/sample.mp4" type="video/mp4"></source>
</video>
{% endblock %}
views.py:
def index(request):
return render(request, "app/videoplay.html", {'media': MEDIA_ROOT})
我从settings.py导入了 MEDIA_ROOT
,这是绝对的媒体目录的路径。
I imported MEDIA_ROOT
from settings.py and it is absolute path of media directory.
开发环境:
browser: chrome
django:1.6.1
python:2.7
静态和媒体目录关系:
mysite/
static/
sample.mp4
media/
sample.mp4
templates/
....
views.py
....
推荐答案
您在文件URL的开头缺少斜杠,并且不需要将MEDIA_ROOT传递到上下文中,使用您在设置文件中设置的{{STATIC_URL}}模板变量。
You're missing the slash at the start of the file URL, and you don't need to pass the MEDIA_ROOT into the context, use the {{ STATIC_URL }} template variable that you set in your settings file.
从下面的评论中,您的MEDIA_ROOT设置是django将存储媒体文件(用户上传)的位置。 django将在STATIC_ROOT中查找静态文件(您的js / css / images等)。
To clarify from the comments below, your MEDIA_ROOT setting is where django will store media files (user uploaded). The STATIC_ROOT is where django will look for static files (your js/css/images etc).
STATIC_URL
模板中使用 MEDIA_URL
设置。它们将被设置为 STATIC_URL = / static /
和 MEDIA_URL = / media /
之类的东西,它们由django传递到模板,因此在执行以下操作时:
The STATIC_URL
and MEDIA_URL
settings are used in the template. They will be set to something like STATIC_URL = "/static/"
and MEDIA_URL = "/media/"
and they are passed to the template by django so when you do:
<img src="{{ STATIC_URL }}sample.jpg" />
或
<source src="{{ MEDIA_URL }}sample.mp4" type="video/mp4"></source>
它将 {{STATIC_URL}}
替换为 / static /
,所以最终得到 / static / sample.jpg
作为django的src网址用于从STATIC_ROOT中提取文件。
it replaces {{ STATIC_URL}}
with "/static/"
so you end up with "/static/sample.jpg"
as the src url which django uses to fetch your file from the STATIC_ROOT.
这篇关于使用Django和html5标签播放视频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!