首页 > 解决方案 > 在 Django 模板中显示视频:媒体链接

问题描述

当前尝试从模型中提取视频,但似乎无法通过将媒体目录添加到提取的 URL 的前面来找到正确的 url。

我是否正确地从模型中提取了 url?

代码 + 生成的 HTML + 控制台日志

Settings.py(媒体部分)

STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

urls.py(在应用程序中)

from django.urls import path
from . import views

urlpatterns = [
    path('', views.video_form_upload, name='highlights'),
    path('outputs', views.video_output, name='output')
]

更新

video_output.html

{% extends 'highlights/base.html' %}

{% block content %}
  {% for video in highlights %}
          <video width="320" height="240" controls>
            {% load static %}
            <source src="{% static "{{ video.highlight.url }}" %}" type="video/mp4"></source>
              Your browser does not support the video tag
          </video>
  {% endfor %}
{% endblock %}

示例输出视频 URL

  <video width="320" height="240" controls>

    <source src="/media/%7B%7B%20video.highlight.url%20%7D%7D" type="video/mp4"></source>
      Your browser does not support the video tag
  </video>

标签: pythonhtmldjangotemplatesdjango-models

解决方案


您需要将媒体 URL 添加到开发中的 urlpatterns。

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

推荐阅读