Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedding Video File in Django Site

Tags:

django

I have a Django site that I'm creating, and I want some of the pages to have videos embedded in them. These videos aren't part of a model. I just want to be able to use the view to figure out which video file to play, and then pass the file path into the template. All the files are hosted locally (for now, at least). Is it possible to do with Django? And if so, how do I do it?

like image 928
Gree Tree Python Avatar asked Oct 17 '22 10:10

Gree Tree Python


1 Answers

There are two ways you can do this -

Method 1: Pass parameter in URL and display video based on that parameter -

If you don't want to use models at any cost, use this, else try method 2.

Assuming you have saved all videos in your media directory and they all have unique names (serving as their ids).

your_app/urls.py -

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^video/(?P<vid>\w+)/$',views.display_video)
    # \w will allow alphanumeric characters or string
]

Add this in the project's settings.py -

#Change this as per your liking
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

your_app/views.py -

from django.conf import settings
from django.shortcuts import render
from django.http import HttpResponse
import os
import fnmatch

def display_video(request,vid=None):
    if vid is None:
        return HttpResponse("No Video")

    #Finding the name of video file with extension, use this if you have different extension of the videos    
    video_name = ""
    for fname in os.listdir(settings.MEDIA_ROOT):
        if fnmatch.fnmatch(fname, vid+".*"): #using pattern to find the video file with given id and any extension
            video_name = fname
            break


    '''
        If you have all the videos of same extension e.g. mp4, then instead of above code, you can just use -

        video_name = vid+".mp4"

    '''

    #getting full url - 
    video_url = settings.MEDIA_URL+video_name

    return render(request, "video_template.html", {"url":video_url})

Then in your template file, video_template.html, display video as -

<video width="400" controls>
  <source src="{{url}}" type="video/mp4">
  Your browser does not support HTML5 video.
</video>

Note: There can be performance issue, iterating through all the files in the folder using os.listdir(). Instead, if possible, use a common file extension or use the next method (strongly recommended).

Method 2 : Storing video ids and correspondig file names in database -

Use same settings.py, urls.py and video_template.html as in method 1.

your_app/models.py -

from django.db import models
class videos(models.Model):
    video_id = models.CharField(blank=False, max_length=32)
    file_name = models.CharField(blank=False, max_length=500)
    def __str__(self):
        return self.id

your_app/views.py -

from django.conf import settings
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from .models import videos

def display_video(request,vid=None):
    if vid is None:
        return HttpResponse("No Video")

    try:
        video_object = get_object_or_404(videos, pk = vid)
    except videos.DoesNotExist:
        return HttpResponse("Id doesn't exists.")

    file_name = video_object.file_name
    #getting full url - 
    video_url = settings.MEDIA_URL+file_name

    return render(request, "video_template.html", {"url":video_url})

So if you want to access any page with video id 97veqne0, just goto - localhost:8000/video/97veqne0

like image 86
Shivendra Singh Avatar answered Oct 21 '22 06:10

Shivendra Singh