python - 您还需要将对象传递给 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)
解决方案
您正在传递一个名为 的对象movie
,因此您应该在模板中使用它:{{ movie.title }}
。
但是我不太明白你在这里做什么。您的模板路径意味着您为每个视频都有单独的模板,这确实很奇怪;您似乎有点错过了模板的意义。模板应该是通用的,所有数据都应该来自上下文。如果您对每个视频都有一个单独的模板,您不妨对所有内容进行硬编码。
推荐阅读
- angular - 如果 'mat-option' 是 Angular 组件,则验证
- java - 如何覆盖 org.springframework.hateoas.Resources 将内容序列化为 List 以序列化名称
- swift - 如何最大化 Cloud Firestore 中的现有数字字段
- c# - AWS Lambda 和 ASP.NET Core 日志记录
- c - 如何在 C 中模拟 const 变量以进行单元测试?
- xml - 需要包含多个循环模式的工作代码不起作用
- spring - Spring - Sock.js - websockets:被 CORS 策略阻止
- c++ - 为什么程序在启动时终止而不输出任何内容?
- php - nikic/FastRoute post请求参数访问
- javascript - 使函数调用同步