0

I have a model 'Product' to upload products.

class Product(BaseModel):
  ...
  ...
  class Meta:
    db_table = TABLE_PREFIX + "product"

I have another table with product as foreignkey.

class ProductImage(BaseModel):
  product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True)
  image = models.ImageField(upload_to='product')

  class Meta:
    db_table = TABLE_PREFIX + "product_image"

In home page i want to display these products. I have the home view as

def home(request):
  category_obj = Category.objects.all()
  product_obj = Product.objects.all().order_by('-id')
  
  context = {
        "title": "Home",
        "product_obj": product_obj,
        "category_obj": category_obj,
  }
  return render(request, "home/index.html", context)

In the template I want to display the products along with the images.

I am able to display all the details in the template except images.

<div class="dFlex product-list-wrap">
  {% for product in product_obj %}
    <div class="img-wrap">
      <img src="" alt="Product Image">
    </div>
    <h4>{{ product.name}}</h4>
    <p>{{ product.description}}</p>
  {% endfor %}
</div>

How do i display images on my template? How can I query images also while querying products?

Thank you

3
  • Here each product can have zero, one or many images, so there is not per se a single image, nor is there per se any image... Commented Jun 13, 2022 at 18:02
  • Does this answer your question? Getting and displaying related objects in Django Commented Jun 13, 2022 at 18:02
  • @AbdulAzizBarkat I think the code is working and i am getting the image as related manager object. I want to display the first image on my template. Can you please show me how to display the first image on template. Thank you. Commented Jun 14, 2022 at 2:25

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.