2014-01-27 71 views
0

我想顯示所有我的圖片在指定的類別在for循環它沒有顯示任何東西,但如果我不使用循環它只顯示一個圖像。所有圖片顯示在類別django

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 

回答

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) 
+0

不錯,tnx ....... – Eriks