2017-06-15 54 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