代码之家  ›  专栏  ›  技术社区  ›  Heero Yuy

Django:如何从产品模型显示ProductImage

  •  0
  • Heero Yuy  · 技术社区  · 8 年前
    class Product(models.Model):
        company = models.ForeignKey('Company', on_delete=models.SET_NULL, null=True)
    
    class ProductImage(models.Model):
        product = models.ForeignKey('Product', on_delete=models.SET_NULL, null=True)
        image_path = models.ImageField(max_length=255,null=True,blank=True,upload_to='images/%Y/%m/%d')
    

    在我看来。py公司

    class HomeView(ListView):
        template_name = "catalog/product_list.html"
        context_object_name = 'product_list'
        model = Product
    

    在product\u列表中。html问题就在这里

    {% if product_list %}           
        {% for product in product_list %}
             <!-- the problem is here -->
             if there is an image show 
             <img src="default" />
             else
             <img src="product.ProductImage.image_path here" />
        {% endfor %}
    {% endif %}  
    

    问题出在product\u列表的迭代中 我试过了,productImage=产品。[productImage或product\u image或它是productImage]。first()但它不起作用

    我也试过了

    {% 
                                img = ''
                                try:
                                    productImage = product.productimage_set.first() 
                                    img = productImage.image_path
                                except ProductImage.DoesNotExist:   
                                    img = ''
                                    %}
                                    <img class="card-img-top" style="height: 225px; width: 100%; display: block;" src="{{product_image.image_path}}" data-holder-rendered="true">
                                    {%
                                %}
    

    但它只输出代码块

    我也试过这个

     {% productImage = product.productimage_set.first() %}
    

    但上面说 “productImage”,应为“empty”或“endfor”。您是否忘记注册或加载此标签?

    2 回复  |  直到 8 年前
        1
  •  2
  •   Aswin Murugesh    8 年前

    您需要使用 url 图像的属性。

    {% for product in product_list %}
        {% for product_image in product.productimage_set.all %}
            <image src="{{ product.image_path.url }}" />
        {% endfor %}
    {% endfor %}
    
        2
  •  0
  •   Andrewjcm    5 年前

    如果您只想发布第一张照片,则不需要第二张for循环。只需使用:

    <image src="{{ product.productimage.all.0.image_path.url }}" />
    

    对不起,我迟到了三年。。。但以防其他人偶然发现这一点。