Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

577
Views
Django object_list from ListView with two models

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 class="product">
        {% 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

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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 %}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!