Home > Blockchain >  Django object_list from ListView with two models
Django object_list from ListView with two models

Time:12-22

I have two models, and need access property from both.

models.py

class Product(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    product_title = models.CharField(max_length=255, default='product_title')    
    product_description = models.CharField(max_length=255, default='product_description')    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    is_active = models.BooleanField(default=True)
    product_view = models.IntegerField(default=0) 

    def __str__(self):
        return self.product_title

    def get_absolute_url(self):
        return reverse('product_change', kwargs={'pk': self.pk})

class ProductImages(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    image_type = models.CharField(max_length=33,default='image_type')    
    image_file = models.ImageField(
        upload_to='images/',
        null=True,
        blank=True,
        default='magickhat-profile.jpg'
    )

ProductImages is a model to store multiple images.

views.py

class ProductListView(ListView):
    model = Product
    template_name = 'product_list.html'

product_list.html

    ...
    {% for product in object_list %}
    <div >
        {% include 'label_perfil.html' %}
        {% include 'data_product.html' %}
    </div>
    {% endfor %}
    ...

data_product.html

{% block data-product %}
<img src="{{ product.image_file }}"/>
{% endblock %}

All properties from Product model is available, but how ca access product.image_file data? That return empty...

Django 3.2

CodePudding user response:

There can be multiple ProductImages for each Product so you don't access a single image_file attribute from the product, you loop over all the ProductImages for that Product and access the images from there

data_product.html

{% block data-product %}
    {% for image in product.productimages_set.all %}
        <img src="{{ image.image_file.url }}"/>
    {% endfor %}
{% endblock %}
  • Related