首页 > 解决方案 > 试图在第一个 Django 项目中实现 HTML 模板。未放映的电影

问题描述

我正在关注一个在线 Python 教程,我必须创建一个 HTML 模板,在该模板中创建一个表格供最终用户查看库存中的电影。我一步一步地按照老师的指示,但是当我刷新浏览器页面时,它只显示了我在 HTML 中列出的类属性。我写的代码如下:

index.html 文件:

<table class="table">
    <thead>
        <tr>
            <th>Title</th>
            <th>Genre</th>
            <th>Stock</th>
            <th>Daily Rate</th>
        </tr>
    </thead>
    <tbody>
        {% for movie in movies %}
            <tr>
                <td>{{ movie.title }}</td>
                <td>{{ movie.genre }}</td>
                <td>{{ movie.number_in_stock }}</td>
                <td>{{ movie.daily_rate }}</td>
            </tr>
        {% endfor %}
    </tbody>
</table>

和 views.py 文件:

from django.http import HttpResponse
from django.shortcuts import render
from .models import Movie


def index(request):
    movies = Movie.objects.all()
    return render(request, 'index.html', {' movies': movies})

这是我的网络浏览器上的结果:

在此处输入图像描述

如果有人知道为什么这不起作用,那么任何帮助都会很棒!

标签: pythonhtmldjangomosh

解决方案


您似乎有一个传递上下文的空间:

return render(request, 'index.html', {' movies': movies})

您需要替换' movies''movies',否则在渲染模板时该变量将无法使用正确的名称。


推荐阅读