2017-02-10 150 views
0

我有產品的圖像,但是當我嘗試顯示圖像只有這個產品django顯示我所有圖像產品如何我可以修復它?我嘗試切片不工作,如果我切片:「0:1」顯示圖像,但不是圖像這個產品。Django只顯示一個元素

class Product(models.Model): 
    category = models.ForeignKey(Category, related_name='product') 
    name = models.CharField(max_length=200, db_index=True) 
    slug = models.SlugField(max_length=200, db_index=True) 
    image = models.ImageField(upload_to='product/%Y/%m/%d', 
           blank=True) 
    description = models.TextField(blank=True) 
    price = models.DecimalField(max_digits=10, decimal_places=2) 
    stock = models.PositiveIntegerField() 
    available = models.BooleanField(default=True) 
    promo = models.BooleanField(default=False) 
    news = models.BooleanField(default=True) 
    section = models.CharField(max_length=50, choices=SECTION_CHOICES, default=None) 
    detailimage = models.ImageField(upload_to='product/detail/%Y/%m/%d', 
            blank=True) 
    detailimagetwo = models.ImageField(upload_to='product/detail/%Y/%m/%d', 
            blank=True) 
class Meta: 
     ordering = ('name',) 
     index_together = (('id', 'slug'),) 

def __str__(self): 
    return self.name 

@property 
def image_url(self): 
    if self.image and hasattr(self.image, 'url'): 
     return self.image.url 

@property 
def detail_url(self): 
    if self.detailimage and hasattr(self.detailimage, 'url'): 
     return self.detailimage.url 

@property 
def detailtwo_url(self): 
    if self.detailimagetwo and hasattr(self.detailimagetwo, 'url'): 
     return self.detailimagetwo.url 

def get_absolute_url(self): 
    return reverse('shop:product_detail', 
        args=[self.id, self.slug]) 

我views.py

def product_detail(request, id, slug): 
    product = get_object_or_404(Product, 
           id=id, 
           slug=slug, 
           available=True) 
    products = Product.objects.all() 

    return render(request, 
        'shop/product/detail.html', 
        {'product': product, 
        'products': products}) 

和我detail.html

{% extends "shop/base.html" %} 
{% load static %} 

{% block title %}{{ product.name }}{% endblock %} 
{% block content %} 
{% for p in products %} 
    <img src="{{p.detail_url}}" class="img-responsive"> 
    {% endfor %} 
    </div> 
</div> 
{% endblock %} 

如果u想somethink更多的評論,我會多快,我可以添加它。

+0

你想只顯示一個產品的使用枕頭的圖像作爲字符串的不僅僅是地址發生變化?因爲你在循環所有產品。你是否從別的地方複製這段代碼? – Mojimi

+0

不,我創建它。我完成了。 Mby很簡單,但我不知道該怎麼做 – KeepItSick

+0

那麼它很難理解你的英語,你的問題是什麼,你的母語是什麼?也許有它的版本的計算器 – Mojimi

回答

0

改變你的看法

def product_detail(request, id, slug): 
    product = get_object_or_404(Product, 
           id=id, 
           slug=slug, 
           available=True) 

    return render(request, 
        'shop/product/detail.html', 
        {'product': product}) 

,並在模板變化

{% for p in products %} 

{% for p in product %} 

您可以通過模板移除一個 'S' 解決這個問題,但我建議改變查看功能如上所述

的情況下,該

{{p.detail_url}} 

{{p.fieldname.url}}