didierCH
didierCH

Reputation: 428

Show ForeignKey in template with class based views

I have a class based DetailView with the model Property as the main model. That model has a foreign key relationship with the model PropertyImage where I store some images. I want to show all related images from PropertyImages in the template detail_view.html together with some details from Property. I know how to do it in a function based view and I tried a lot of things but I failed all the time. Maybe it's just some tiny thing but I don't get it to work.

Here is my code:

# models.py

from django.db import models


class Property(models.Model):
    title = models.CharField(max_length=140, default="Title",)
    description = models.TextField(max_length=2000)
    # ... and some more fields

    def __str__(self):
        return self.title

class PropertyImage(models.Model):
    property = models.ForeignKey(Property, on_delete=models.CASCADE, related_name='images')
    image = models.ImageField(upload_to='images/')
    figcaption = models.CharField(max_length=160)

    def __str__(self):
        return self.figcaption[:50]
# views.py

from django.views.generic import DetailView

from .models import Property


class PropertyDetailView(DetailView):
    model = Property
    template_name = 'property_detail.html'

For quicker assessment look at the <!-- Here I'm stuck -->section:

<!-- property_detail.html -->

{% extends 'base.html' %}

{% block content %}
    <div class="container">
        <div class="property-entry">
            <img src="{{ property.cover_image.url }}" alt="{{ property.title }}" class="img-fluid">
            <h2>{{ property.title }}</h2>
            <p>Description: {{ property.description }}</p>

            <!-- Here I'm stuck -->
            {% for image in property.propertyimage_set.all %}
            <img src="{{ image.image.url }}">
            <p>{{ image.figcaption }}</p>
            {% endfor %}
        </div>
    </div>


{% endblock content %}

I appreciate your help.

Upvotes: 2

Views: 674

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476813

Since the related_name=… of your ForeignKey to Property is set to related_name='images', to access the images in reverse, it is property.images.all:

{% for image in property.images.all %}
    <img src="{{ image.image.url }}">
    <p>{{ image.figcaption }}</p>
{% endfor %}

Upvotes: 3

Related Questions