如何使用基于 Class 的视图 DetailView 将我的图片库放入 Django 中的 product.html

How to get my image gallery into my product.html in Django with Class based view DetailView

我正在使用模型产品和图像。我的目标是在我的单个项目页面中显示来自模型“图像”的项目相关图片库

我如何更改以下代码以按项目 slug 过滤并仅显示特定于 slug 的图库。

Item class

class Item(models.Model):
    title = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    image = models.ImageField(, upload_to='catalog/images/', blank=True)
    slug = models.SlugField()

Images class

class Images(models.Model):
    item = models.ForeignKey(Item, on_delete=models.CASCADE)
    title = models.CharField(blank=True, max_length=50)
    image = models.ImageField(upload_to='catalog/images/', blank=True)

Product detail view

class ProductDetailView(DetailView):
    model = Item
    template_name = 'product.html'
    context_object_name = 'item'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['image_gallery'] = Images.objects.all()
        return context

product.html page

<div class="row wow fadeIn">
        
        {% for img in image_gallery %}
          
        <div class="col-lg-4 col-md-12 mb-4">
          
          <img src="{{img.image.url}}" class="img-fluid" alt="">
          
        </div>

您需要使用 .filter() 而不是 .get()

image = Images.objects.all()
image.image will give you the image

这是 Django 3,您需要将其转换为您正在使用的任何版本

你可以通过self.object访问image的实例,那么你只需要通过外键关系过滤你要传递给view的image即可。

class ProductDetailView(DetailView):
    model = Item
    template_name = 'product.html'
    context_object_name = 'item'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['image_gallery'] = Images.objects.filter(item=self.object)
        return context