0

I am trying to use a custom filter to find the video duration using moviepy however the function is not able to access the files even though it seems the correct video path is being passed into the function in the custom filter.

I'm getting the following error:

OSError at /tape/tape/
MoviePy error: the file /media/video_files/channel_Busy/171003B_026_2k.mp4 could not be found!
Please check that you entered the correct path.

The custom filter:

vduration.py

from django import template
import moviepy.editor
register = template.Library()

@register.filter(name='vduration')
def vduration(videourl):
    
    video = moviepy.editor.VideoFileClip(videourl)
    video_time = int(video.duration)
    return video_time

views.py

def tape(request):
    tapes=VideoFiles.objects.all()
    context={
        "videos": tapes,
    }
    return render(request, "tape/tape.html", context)

tape.py

{% for video in videos %}
  <div class="video-time">{{video.video.url | vduration}}</div>
 {% endfor %}

models.py

class VideoFiles(models.Model):
    id=models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    video=models.FileField(upload_to=channel_directory_path)

    def get_absolute_url(self):
        return reverse('video_watch', args=[str(self.id)])

    def __str__(self):
        return f"video_file_{self.id}"

1 Answers1

0

Use the absolute path of the media file.

vduration.py

import os
from django import template
import moviepy.editor
from your.settings.file import BASE_DIR 

register = template.Library()

@register.filter(name='vduration')
def vduration(videourl):
    
    video = moviepy.editor.VideoFileClip(os.path.join(BASE_DIR, videourl))
    video_time = int(video.duration)
    return video_time
Messaoud Zahi
  • 1,214
  • 8
  • 15
  • It seems BASE_DIR is only returning "C:/" and concatenating the relative part of the video URL instead e.g C:/media/video_files/channel_Busy/171003B_026_2k.mp when the actual absolute path is C:/Users/User/Desktop/Site/media/video_files/channel_Busy171003B_026_2k.mp4. Only concatenating ("C:/Users/User/Desktop/Site" + videourl) has worked but I do not want to hardwire this. Any ideas? – Immortal Noob Jan 23 '22 at 20:40
  • in your `settings.py` do you have this line `BASE_DIR = os.path.dirname(os.path.dirname(__file__))` – Messaoud Zahi Jan 23 '22 at 20:47
  • no but in the pre written code it came as `BASE_DIR = Path(__file__).resolve().parent.parent` instead. – Immortal Noob Jan 23 '22 at 21:09
  • Add it to your `settings.py` under another variable name and use it in your filter. `os.path.dirname(os.path.dirname(__file__))` will give you `C:/Users/User/Desktop/Site` – Messaoud Zahi Jan 23 '22 at 21:14
  • I Don't know what I'm doing wrong but still getting the same result – Immortal Noob Jan 23 '22 at 21:22