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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With