Django只显示一个元素

时间:2017-02-10 15:19:33

标签: django-models django-templates django-views

我有图像的产品但是当我尝试显示图像时,这个产品django向我展示了所有图像产品我如何解决它?如果我这样做的话,我会尝试一下工作,但是如果我做的话:" 0:1"给我看图像但不是这个产品的图像。

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 %}

如果你想要更多评论,我会加快它的速度。

1 个答案:

答案 0 :(得分: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'来解决问题,但我建议更改视图功能,如上所述

如果您使用Pillow而不仅仅是图像的地址作为字符串更改

{{p.detail_url}}

{{p.fieldname.url}}