tim
tim

Reputation: 379

How to display ForeignKey object in ListView - Django

I have read up on this but I can't find something which solves my issue.

I am trying to display a table with a list of products with thumbnails. The thumbnail field in the table returns no url, but returns a broken image link only for the products which own a thumbnail.

This list of products uses a ListView, and I can display the thumbnail fine in the detail view of the product (a DetailView) which uses the same template code

What do I need to do to display the thumbnail for each product in the ListView... ie. how must I change my queryset to pass the thumbnail into the template along with the product?

View

class ProductView(generic.ListView):
    template_name = 'product/product.html'
    context_object_name = 'product_list'

    def get_queryset(self):
        return Product.objects.all()

Template

    {% for product in product_list %}
        <tr>
            <td><a href="/product/{{ product.id }}/">{{ product.title }}</a></td>
            <td>    {% if product.thumbnails.all %}
                    <img src="{{ product.thumbnail.url }}" alt="...">
                    {% endif %}
            </td>
            <td>{{ product.category }}</td>
            <td>{{ product.subcategory }}</td>
            <td>{{ product.status }}</td>
            <td>{{ product.date_added }}</td>
    {% endfor %}

Model

class ProductThumbnail(models.Model):   
    product = models.ForeignKey(Product, default=None, related_name='thumbnails')
    thumbnail = models.ImageField(upload_to='thumbnails/',
                          verbose_name='thumbnail', blank=True,)

Please let me know if any more information is needed.

Upvotes: 1

Views: 2401

Answers (2)

Augusto Destrero
Augusto Destrero

Reputation: 4355

If you have only one thumbnail per Product, you should add the field

thumbnail = models.ImageField(upload_to='thumbnails/',
                      verbose_name='thumbnail', blank=True)

directly to the model Product and ditch the ProductThumbnail model. The way you designed your DB makes possible to have more thumbnails for each product (one-to-many relationship), but this makes your code needlessly complex.

If thumbnail was a field of the Product model, you could do simply:

{% if product.thumbnail %}
   <img src="{{ product.thumbnail.url }}" alt="...">
{% endif %}

Upvotes: 1

Iain Shelvington
Iain Shelvington

Reputation: 32244

{% if product.thumbnails.all %} should be {% if product.thumbnail %}

{% if product.thumbnails.all %} would only make sense if product.thumbnails was a reverse relation

EDIT: I misread the question

You need to loop through the thumbnails {% for thumbnail in product.thumbnails.all %}

Upvotes: 2

Related Questions