我想显示所有在指定类别中的照片在for循环中它没有显示任何内容,但如果我不使用for循环它只显示一个图像。
views.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)
lists.html
{% for image in images %}
<a href="#"><img src="{{ image.image.url }}" style="width:200px; height: 200px; float:left;"/></a>
{% endfor %}
models.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
答案 0 :(得分:3)
问题在于您的观点。使用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)