python - 类型对象 'Video' 没有属性 'video_file' django

标签 python html django

我试图在我的网站上显示 mp4,并将其放入上下文中,但由于某种原因,当我访问该页面时,我得到以下信息:“类型对象“视频”没有属性“video_file”

尝试了一些方法,但没有一个起作用。

Views.py

def movie(request, movie_id):
    movie = get_object_or_404(Video, title=movie_id) # This only gets the movie name
    mp4 = Video.video_file.url
    context = {'video': movie, 'mp4':mp4}
    return render(request, template_name=f'uploadvideos/movie.html', context=context)

models.py

class Video(models.Model):
    title = models.CharField(max_length=40, blank=False)
    video_file = models.FileField(name="Upload a mp4 file",
                                  upload_to=f"uploadvideos/video",
                                  validators=[FileExtensionValidator(['mp4'])],
                                  blank=False)

    def __str__(self):
        return self.title

电影.html

    <h1 class="movietitle">{{ video }}</h1>
    <div class="videoDetails">
        <video width="700" height="430" controls>
            <source src="{{ mp4 }}" type="video/mp4">
        </video>
    </div>

我预计会显示视频,但我收到了此错误: '类型对象'Video'没有属性'video_file'

最佳答案

Video 引用 Video ,因为 Video 实例这里被命名为movie,因此你应该使用:

def movie(request, movie_id):
    movie = get_object_or_404(Video, title=movie_id)
    context = {'video': movie, 'mp4': <b>movie.video_file.url</b> }
    return render(request, 'uploadvideos/movie.html', context)

你的假设:

# This only gets the movie name

是错误的。这将加载一个 Video 对象。如果您渲染这个对象,它将调用该对象上的str(..)函数,这确实会返回标题,但这不会 表示 movie 本身是一个字符串。

关于python - 类型对象 'Video' 没有属性 'video_file' django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56724885/

相关文章:

javascript - 有没有更有效的方式来显示 DOM 元素

python - 需要 Microsoft Visual C++ 14.0。用 "Microsoft Visual C++ Build Tools": http://landinghub. visualstudio.com/visual-cpp-build-tools 获取

python - Django - 在自定义模型函数中访问相关模型

python - 如何减少 django 模型 has_relation 方法中的查询?

python - 将字符串从 html 搜索框传递给 python 函数

python - 将两个整数列表组合成一个字符串列表

python - 使用 sqlalchemy_utils ChoiceType 在 Flask 中迁移时出错

python - 在 key /证书不匹配的情况下测试 TLS 证书身份验证

javascript - $.ajax 请求值返回 [object Object]

jquery - 悬停到纯色背景?