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”。您是否忘记注册或加载此标签?