2017-06-15 162 views
1

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

+1

,你可能觉得https://github.com/jazzband/django-embed-video – nik

+1

看看你不不需要为此提供赏金答案是肯定的,这是可能的。 – e4c5

回答

2

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

方法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') 

your_app/views.py -

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

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 

    ''' 
     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和correspondig文件名中的数据库 -

使用相同的settings.py,urls.py和video_template.html如方法1

your_app /模型的.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}) 

所以,如果你想访问与视频ID 97veqne0任何页面,只需转到 - localhost:8000/video/97veqne0