首页 > 解决方案 > 您还需要将对象传递给 views.py 中的模板

问题描述

一位用户告诉我将对象传递给 views.py 中的模板

我在 django 中创建了一个模型,并希望在我的 html 代码中显示我使用该模型创建的对象的标题。我的模型代码是:

class Video(models.Model):
    title = models.CharField(max_length=40, blank=False)

    def __str__(self):
        return self.title

我的html代码是:

<html>
<body>
    <header>
        <div class="container">
            <!-- Branding -->
            <a href="/"><span class="branding">Movies & Other</span></a>
            <a href="/admin"><span class="adminpanel">Admin panel</span></a>
        </div>
    </header>

    <h1 class="movietitle">{{ video.title }}</h1>
    <div class="videoDetails">
        <video width="700" height="430" controls>
            <source src="uploadvideos/videos/yt/yt.mp4" type="video/mp4">
        </video>
    </div>
</body>
</html>

我在管理面板的视频模型中创建了一个对象,但它没有显示它的标题。

这是我的意见.py

def index(request):
    movie_list = Video.objects.order_by('id')
    context = {'video_list': movie_list}
    return render(request, template_name='uploadvideos/index.html', context=context)


def movie(request, movie_id):
    movie = get_object_or_404(Video, title=movie_id)
    context = {'movie': movie}
    # return HttpResponse(f"You're viewing {movie.title}")
    return render(request, template_name=f'uploadvideos/{movie.title}/movie.html', context=context)

标签: pythonhtmldjango

解决方案


您正在传递一个名为 的对象movie,因此您应该在模板中使用它:{{ movie.title }}

但是我不太明白你在这里做什么。您的模板路径意味着您为每个视频都有单独的模板,这确实很奇怪;您似乎有点错过了模板的意义。模板应该是通用的,所有数据都应该来自上下文。如果您对每个视频都有一个单独的模板,您不妨对所有内容进行硬编码。


推荐阅读