在Django中使用For循环和If条件在引导转盘中显示图像

2024-09-30 06:30:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在到处寻找类似的案例,但没有找到任何可以解决我问题的方法。我想在for循环中显示来自html中模型的图像,该循环具有if条件。这是my models.py:

from django.db import models

# Create your models here.


class CarouselItem(models.Model):
    carousel_picture = models.ImageField(upload_to='carousel_images/', null=True, blank=True)

views.py:

from django.shortcuts import render
from .models import CarouselItem

# Create your views here.


def index(request):
    carousel_items = CarouselItem.objects.all()
    context = {
        'carousel_items': carousel_items
    }
    return render(request, "home/index.html", context=context)

和我的html:

    {% if carousel_items %}
<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
  <div class="carousel-inner">
  {% for item in carousel_items %}
      {% if forloop.first %}
        <div class="carousel-item active">
          <img src="{% item.carousel_picture.url %}" class="d-block w-100" alt="...">
        </div>
      {% else %}
        <div class="carousel-item">
          <img src="{% item.carousel_picture.url %}" class="d-block w-100" alt="...">
        </div>
      {% endif %}
  {% endfor %}
  <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>
{% else %}
    <h3>We are sorry, there are currently no Images to display</h3>
{% endif %}

当我想要访问与html关联的页面时,我会收到以下错误消息:

Invalid block tag on line 86: 'item.carousel_picture.url', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag?

我觉得我在别的地方犯了一个错误,但我不知道那是什么。我使用的是Bootstrap4.5.3和Django3.1.5

此项目中的所有其他html文件都没有使用for循环显示图像的问题


Tags: fromimportdivforifmodelshtmlitems
1条回答
网友
1楼 · 发布于 2024-09-30 06:30:34

而不是使用:

{% item.carousel_picture.url %}

对于模板逻辑,请使用:

{{ item.carousel_picture.url }}

它使用该值

相关问题 更多 >

    热门问题