在Django网站中嵌入视频文件

5

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

在Django中是否可以实现这一点?如果可以,如何实现?


1
你可能想要查看 https://github.com/jazzband/django-embed-video - Nikhil N
1
你不需要为此提供赏金,答案是肯定的,这是可能的。 - e4c5
1个回答

3

您可以通过以下两种方法来实现 -

方法1:在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
]

把下面的代码添加到项目的settings.py文件中 -
#Change this as per your liking
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

你的应用程序/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})

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

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

注意:使用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

您的应用程序/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})

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接