django - 在 Django 站点中嵌入视频文件

标签 django

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

最佳答案

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

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

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

关于django - 在 Django 站点中嵌入视频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44559074/

相关文章:

python - 为什么我在 Django 中收到表单无效错误?

Django,如何以自定义形式使用管理自动填充字段

database - Django 设计 : storing and retrieving text files

python - 警告 : cannot find svn location for distribute==0. 6.16dev-r0

python - django 脆皮表单按钮不显示

python - django-paypal发票已经支付

Django auth.models.User 未经过身份验证,但存在于 auth 数据库中

python - 如何在基于类的 View 中使用 user_passes_test 装饰器?

Django Admin list_filter 和带注释字段的排序

python - 只读 Django 对象管理器?