在 Django 站点中嵌入视频文件

Gre*_*hon 5 django

我有一个正在创建的 Django 站点,我希望其中一些页面嵌入视频。这些视频不是模型的一部分。我只是希望能够使用视图来确定要播放的视频文件,然后将文件路径传递到模板中。所有文件都在本地托管(至少目前是这样)。可以用 Django 做吗?如果是这样,我该怎么做?

Shi*_*hen 3

有两种方法可以做到这一点 -

方法一:在URL中传递参数并根据该参数显示视频 -

如果您不想不惜一切代价使用模型,请使用此方法,否则请尝试方法 2。

假设您已将所有视频保存在媒体目录中,并且它们都有唯一的名称(作为它们的 id)。

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
]
Run Code Online (Sandbox Code Playgroud)

将其添加到项目的 settings.py 中 -

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

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})
Run Code Online (Sandbox Code Playgroud)

然后在模板文件 video_template.html 中,将视频显示为 -

<video width="400" controls>
  <source src="{{url}}" type="video/mp4">
  Your browser does not support HTML5 video.
</video>
Run Code Online (Sandbox Code Playgroud)

注意:使用 os.listdir() 迭代文件夹中的所有文件可能会出现性能问题。相反,如果可能,请使用通用文件扩展名或使用下一个方法(强烈推荐)。

方法2:在数据库中存储视频ID和相应的文件名 -

使用与方法 1 中相同的 settings.py、urls.py 和 video_template.html。

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
Run Code Online (Sandbox Code Playgroud)

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})
Run Code Online (Sandbox Code Playgroud)

因此,如果您想访问视频 ID 为 97veqne0 的任何页面,只需转到 -localhost:8000/video/97veqne0