Как запросить путь к изображению с правильным условием if из шаблона Django?

В Django у меня есть модель коробки. Каждая коробка имеет несколько изображений, связанных с этой коробкой.

from django.db import models
from products.models import Product

# Create your models here.
class Box(models.Model):
    boxName = models.CharField(max_length=255, blank = False)
    boxDescription = models.TextField()
    boxPrice = models.DecimalField(max_digits=9, decimal_places=0, default=0)
    boxSlug = models.SlugField(max_length = 255, unique = True, help_text = "Unique text for url created from box name")
    boxCreatedAt = models.DateTimeField(auto_now_add=True)
    boxUpdatedAt = models.DateTimeField(auto_now=True)
    product = models.ManyToManyField(Product)

    def __str__(self):
        return self.boxName
    
    class Meta:
        db_table = 'boxes'
        ordering = ['-boxName']

class BoxImage(models.Model):
    image = models.ImageField()
    imageMetaKeyWords = models.CharField("Meta keywords for SEO", max_length = 255,
    help_text = "Comma delimited words for SEO")
    imageMetaDescription = models.CharField("Meta description", max_length = 255,
    help_text = "Content for image meta tag description")
    defaultImage = models.BooleanField(default= False)
    box = models.ForeignKey(Box, on_delete=models.CASCADE, related_name="images")

В views.py мне нужно поместить все ячейки в контекст, чтобы их можно было передать в шаблон

from django.shortcuts import render
from django.views import View
from index.views import createNavContent
from box.models import Box

# Create your views here.
class MainShop(View):
    def __init__(self):
        context = createNavContent()
        self.context = context.context
        
    def get(self, request, *args, **kwargs):
        self.context['title'] = 'Dimsum Box Shop'
        self.context['boxes'] = Box.objects.filter().all()
        return render(request, template_name='mainShop.html', context = self.context)

Как написать код в шаблоне, чтобы изображение для каждого блока отображалось только тогда, когда defaultImage установлен в True? В приведенном ниже коде {% for image in item.images.filter().all() %} не работает. Элементом является каждая коробка, и мне нужно просмотреть изображения, связанные с каждой коробкой, и только если изображение с defaultImage установлено в True будет отображено.

<div class="container-fluid h-100">
  <h1 class="headerTitle">DIMSUM BOX</h1>
  <hr class = "cardDeckHorisontalLine">
  <div class="row">
    <div class="card-deck justify-content-center">
      {% for item in boxes %}
        <div class="col-auto mt-5">
            <div class="card h-100 text-center" style="width: 18rem;">
              <div class="card-body">
                <!--Title -->
                <h5 class="card-title">{{ item.boxName }}</h5>
                
                <!--Loop over the images for the box, and only show the default image in the card-->
                <!--Product image with link -->
                {% for image in item.images.filter().all() %}
                  display image path here!!!!!!!!
                {% endfor %}
                <!--Product description-->
                <p class="card-text">{{item.boxDescription}}</p>
                
                <!--Allergic note -->
                {% if item.allergic_note %}
                  <p class="card-text">{{ item.product.allergic_note }}</p>
                {% endif %}

                <!--Price-->
                <h5 class="mt-4">{{item.boxPrice}},- </h5>

                <div class="input-group">
                  
                  <div class="input-group-prepend">
                    <button class="btn btn-outline-secondary subtractItem" type="button" id="btn_subtract_{{item.product.slug}}" onclick="itemQuantityChangeButton(this)">
                      -
                    </button>
                  </div>

                  <input type="text" class="form-control" id="text_{{ item.product.slug }}" placeholder="{{item.quantity}}" aria-label="ordered amount" aria-describedby="basic-addon1" readonly>

                  <div class="input-group-append">
                    <button class="btn btn-outline-secondary addOneItem" type="button" id="btn_add_{{item.product.slug}}" onclick="itemQuantityChangeButton(this)">
                      +
                    </button>
                  </div>
                </div>

              </div>
            </div>
          </div>
      {% endfor %}
    </div>
  </div>
</div>

Этот пост очень помог мне. Мое решение заключается в том, что я сначала добавил метод getDefaultImage в класс Box. Это вернет правильное изображение в правильном defaultImage условии.

class Box(models.Model):
    boxName = models.CharField(max_length=255, blank = False)
    boxDescription = models.TextField()
    boxPrice = models.DecimalField(max_digits=9, decimal_places=0, default=0)
    boxSlug = models.SlugField(max_length = 255, unique = True, help_text = "Unique text for url created from box name")
    boxCreatedAt = models.DateTimeField(auto_now_add=True)
    boxUpdatedAt = models.DateTimeField(auto_now=True)
    product = models.ManyToManyField(Product)

    def __str__(self):
        return self.boxName

    def getDefaultImage(self):
        for image in self.images.filter().all():
            if image.defaultImage:
                return image
    
    class Meta:
        db_table = 'boxes'
        ordering = ['-boxName']

В шаблоне я вызвал getDefaultImage, который возвращает нужное изображение для отображения.

<img class="card-img embed-responsive-item" src="{% get_media_prefix %}{{ item.getDefaultImage.image }}" alt="{{item.meta_description}}">
                  {{ item.getDefaultImage.image }}
Вернуться на верх