简体   繁体   中英

Playing Video with Django and html5 tag

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

and in inspect elements:

得到错误

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}) 

I imported MEDIA_ROOT from settings.py and it is absolute path of media directory.

develop environment:

browser: chrome 
django:1.6.1
python:2.7

static and media directories' relation:

mysite/
      static/
            sample.mp4
      media/
            sample.mp4
      templates/
            ....
      views.py
      ....

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.

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).

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" />

or

<source src="{{ MEDIA_URL }}sample.mp4" type="video/mp4"></source>

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.

you can try this :

{% load staticfiles %}
<!DOCTYPE html>
<html>
<body>

<video width="530" height="440" controls autoplay>
  <source src="{% static "mov_bbb.mp4" %}" type="video/mp4"> </source>
</video>
</body>
</html>

setting.py

STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"), )

view.py

from django.views.generic.base import TemplateView


class HomeView(TemplateView):

    template_name = 'home.html'

urls.py

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.HomeView.as_view(), name='home'),
]

static file:

static/
            mov_bbb.mp4

You don't want the absolute path to your directory. You want the URL that the media is actually being served on, which might be something like "/static/sample.mp4" (or however you've configured STATIC_URL .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM