所有图片都显示在djang类别中

2024-04-24 22:28:42 发布

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

我想在for循环中显示我所有的图片,它不显示任何内容,但如果我不使用for循环,它只显示一个图像。你知道吗

你知道吗视图.py你知道吗

def lists(request, category_id):
    image = get_object_or_404(Image, pk=category_id)
    context = {'image': image}
    return render(request, 'photo/lists.html', context)

你知道吗列表.html你知道吗

    {% for image in images %}
        <a href="#"><img src="{{ image.image.url }}" style="width:200px; height: 200px; float:left;"/></a>
    {% endfor %}    

你知道吗型号.py你知道吗

class Image(models.Model):
    title        = models.CharField(max_length=255)
    slug         = models.SlugField(unique=True, max_length=255)
    category     = models.ForeignKey('Category')
    description  = models.CharField(max_length=255)
    published    = models.BooleanField(default=False)
    created      = models.DateTimeField(auto_now_add=True)
    image        = models.ImageField(upload_to="images")

    def __unicode__(self):
        return u'%s' % self.title


class Category(models.Model):
    title        = models.CharField(max_length=255)
    slug         = models.SlugField(unique=True, max_length=255)

    def __unicode__(self):
        return u'%s' % self.title

Tags: pyimageselftrueforreturntitlemodels
1条回答
网友
1楼 · 发布于 2024-04-24 22:28:42

问题在于你的观点。使用get_object_or_404将只返回一个对象。改用filter

def lists(request, category_id):
    images = Image.objects.filter(category__id=category_id)
    context = {'images': images}
    return render(request, 'photo/lists.html', context)

相关问题 更多 >