Neel Sharma
Neel Sharma

Reputation: 53

Playing uploaded video with Django

I am not able to play video on my Django website. I think something is wrong in my views.py render function

videoplay.html:

{% block contents %}
  <video name='demo' controls autoplay width='50%' height='40%'>
    <source src="{{STATIC_URL}}sample1.mp4" type="video/mp4"></source>
  </video>
{% endblock %}

Included this in settings.py:

 STATIC_URL = '/static/'
 STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
 MEDIA_URL = '/media/'
 MEDIA_ROOT = os.path.join(BASE_DIR, 'media')`

Views.py is:

 from django.shortcuts import render, redirect
 from django.conf import settings
 from django.core.files.storage import FileSystemStorage
 from django.views.generic.base import TemplateView
 from uploads.core.models import Document
 from uploads.core.forms import DocumentForm
  def index(request):
     return render(request, "core/videoplay.html")`

I am getting a play button and streaming line on my website

Upvotes: 3

Views: 5035

Answers (1)

Marcus Lind
Marcus Lind

Reputation: 11450

The STATIC_URL is where your static files are located such as CSS, Template Images, Javascript etc. There is a special Template Tag for Static Files in Django called {% static %}.

To generate the full url to where the static files are located, you use the template tag like this:

{% load static %}
<video src="{% static "/videos/demo.mp4" %}">

The MEDIA_URL is where your media files are located. Media files are uploaded files that change during the applications lifetime. They are not necessarily there at deployment but can be uploaded at any time by users or admins on the website.

Media files are set as fields on the model like this:

class DemoVideo(models.Model):
    video = models.FileField(upload_to="videos")

They are accessed like this demovideo.video.url so in your template it would be src="{{demovideo.video.url}}.

Check if your file is a media or static file, and access it in the template in the correct way described above.

Upvotes: 4

Related Questions