Issue
I have a problem with the images, they are not displayed in the template, can someone help me with some solution
class Product(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
myshop = models.ForeignKey(MyShop, on_delete=models.CASCADE, related_name="shop_product")
title = models.CharField(max_length=255)
description = models.TextField(blank=True)
class ProductImage(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product_image")
image = models.ImageField(upload_to='products/images',
validators=[validate_image_file_extension, validate_file_size,
FileExtensionValidator(['JPEG', 'JPG', 'PNG'])])
{% for product in products %}
{% for image in product.product_image.all %}
{% if image.is_feature %}
<img src="{{ image.image.url }}" alt="" width="80" height="80">
{% endif %}
{% endfor %}
{% endfor %}
products = Product.prod_obj.select_related(
'myshop'
).filter(id__in=product_ids).values_list('myshop', 'title', 'description', 'product_image', named=True)
Solution
Don't use .values_list()
[Django-doc] or .values()
[Django-doc]: it removes the model logic layer, and thus as a result, you can indeed no longer access .url
.
Query with:
products = Product.prod_obj.select_related('myshop').prefetch_related(
'product_image'
).filter(id__in=product_ids)
For more information, see this article on (over)use of .values()
I wrote.
Answered By - Willem Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.