Django打印列表显示空白字段

时间:2018-04-26 14:24:45

标签: python django django-templates

我正在尝试使用Django将数据库列表打印到html页面上。

我的模型定义为:

class Drink(models.Model):
    drink_name = models.CharField(max_length=100)
    strength = models.IntegerField(default=0)
    def __str__(self):
        return self.drink_name

定义为的视图:

from django.shortcuts import render

from .models import Drink

# Create your views here.
def index(request):
    served_drinks = Drink.objects.order_by('strength')
    context = {'served_drinks': served_drinks}
    return render(request, 'tavern/index.html', context)

一个模板:

<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Title</title>
</head>
<body>
Welcome to the tavern.<br><br>
{% if served_drinks %}
    <ul>
    {% for drink in served_drinks %}
        <li>{{ Drink.drink_name }} with a strength of {{ Drink.strength }}</li>
    {% endfor %}
    </ul>
{% else %}
    <p>No drinks are available.</p>
{% endif %}

{{served_drinks}}

</html>

模板运行时会生成:

Welcome to the tavern.

with a strength of
with a strength of
with a strength of
with a strength of

<QuerySet [<Drink: Water>, <Drink: Wine>, <Drink: Ale>, <Drink: Black Ale>]>

我为每个项目获得了一行,但没有饮料名称。当我返回模板标签{{served_drinks}}时,我可以看到那里的项目,所以我认为我的行有问题: <li>{{ Drink.drink_name }} with a strength of {{ Drink.strength }}</li>

为什么{{ Drink.drink_name }}在这种情况下不会返回饮品的名称?

1 个答案:

答案 0 :(得分:2)

你有变量名称的拼写错误。 Drink应为drink

{% for drink in served_drinks %}
        <li>{{ Drink.drink_name }} with a strength of {{ Drink.strength}}</li>
{% endfor %}

更正后的代码,

{% for drink in served_drinks %}
        <li>{{ drink.drink_name }} with a strength of {{ drink.strength}}</li>
{% endfor %}