0

首先很抱歉我的英语不好,但我是法国人。我目前正在开发一个 django 应用程序,我正在尝试使我的 HTML 页面工作,但它不会,我不知道为什么。我按照教程进行操作,但我编辑了一些代码以符合我的目的。现在我的页面不会打印出我的变量。我有 python 2.7.5 和 Django 1.11.29

我的html页面

现在这是我的 HTML 代码:

{% if True %}
        <p> Vrai </p>
        <li>{{ Thriller.title }}</li>
{% else %}
        <p> faux </p>
{% endif %}
<ul>
<p> Paragraphe : </p>
    <li>{{ Thriller.title }}</li>
        <li>{{ Thriller.id }}</li>
</ul>

我的 Django 部分代码:

这是在 models.py 文件中:

from django.db import models
import datetime
from django.utils.encoding import python_2_unicode_compatible
from django.utils import timezone

class Artist(models.Model):
        name = models.CharField(max_length=200, unique=True)
        def __str__(self):
                return self.name

class Album(models.Model):
        reference = models.IntegerField(null=True)
        created_at = models.DateTimeField(auto_now_add=True)
        available = models.BooleanField(default=True)
        title = models.CharField(max_length=200, unique=True)
        picture =  models.URLField()
        artists = models.ManyToManyField(Artist, related_name='albums', blank=True)
        def __str__(self):
                return self.title

这是在 views.py 文件中:

from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse
from .models import Album, Artist, Contact, Booking
from django.template import loader

def index(request):
        albums = Album.objects.order_by('-created_at')
        context = {'albums = ': albums}
        template = loader.get_template('polls/index.html')
        return HttpResponse(template.render(context, request))

这也是我在这里的第一篇文章,我真的不知道这篇文章是好还是不好,如果它不好,请原谅!

你想问我什么都可以。谢谢 !

4

2 回答 2

0

您需要在模板中调用您的上下文变量,而不是{{ Thriller.title }}因为您没有Thriller在视图的上下文中指定。

您在 index() 视图中的上下文:

context = {'albums = ': albums}

将此编辑为:

context = {'albums': albums}

然后在您的模板中,例如循环遍历所有专辑标题:

添加了 if 语句:

{% for album in albums %}
    {% if album.title == "Thriller" %}
        <p>{{ album.title }}</p>
    {% endif %}
{% endfor %}
于 2021-03-12T14:45:02.580 回答
0

尝试对您的上下文进行此更改

context = {'albums': albums}

然后在你的模板中做......

{% for album in albums %}
    <p>{{ album.title }}</p>
{% endfor %}
于 2021-03-12T14:53:59.800 回答