Following relationships “backward” for multiple images

I need to display multiple images linked to a single property, and am using two models to do this, one with a ForeignKey to the other. As a first step, I’m just including the models in to upload data there myself. I am able to upload the images fine.

No matter what I can’t manage to get this very simple behaviour to work, I’ve looked at multiple threads elsewhere but must be missing something fundamental. I’ve tried a lot of different ways to handle this, I’ll paste my most recent attempt below, thanks for any help.

class Property(models.Model):
    """Model representing a property."""
    title = models.CharField(max_length=200)
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this property')
    summary = models.TextField(max_length=1000,
        help_text='Enter a brief description of the property.')
    guests = models.IntegerField(
            MinValueValidator(1,message='There is a minimum one person per booking!'),
            MaxValueValidator(10000,message='That is too many.')
    description = models.TextField(max_length=1600, help_text='Enter a longer description of the property.')
    location = models.ForeignKey(
    beds = models.IntegerField(
            MinValueValidator(1,message='There is a minimum one bed per property!'),
            MaxValueValidator(10000,message='That is too many.')
    bathrooms = models.IntegerField(
            MinValueValidator(1,message='There is a minimum one bathroom per property!'),
            MaxValueValidator(10000,message='That is too many.')
    host = models.TextField(max_length=80, help_text='Enter the name of the host')

    def __str__(self):
        """String for representing the Model object."""
        return f'{self.title}'

    def get_absolute_url(self):
        """Returns the url to access a detail record for this book."""
        return reverse('property-detail', args=[str(])

    def grouped(l, n):
    # Yield successive n-sized chunks from l.
        for i in xrange(0, len(l), n):
            yield l[i:i+n]

def get_image_filename(instance, filename):
    title = instance.my_property.title
    slug = slugify(title)
    return "property_images/%s-%s" % (slug, filename)  

class PropertyImages(models.Model):
    """Images for a model"""
    my_property = models.ForeignKey(
    images = models.ImageField(

class PropertyListView(generic.ListView):
    '''Generic view to query database and get all records for Property'''
    model = Property
    paginate_by = 10

urlpatterns = [
    path('properties/', views.PropertyListView.as_view(), name='properties'),

property_list.html (simplified just to display image from each property

{% for property in property_list.all %}
  {{ property.title }}
    <img src="{{ property.images.url }}">
{% endfor %}

What is going wrong with this attempt?

What errors are you seeing, or what behavior is happening that you’re not expecting to have happen?

edited post to include the brackets around property.images.url which I’d missed.

I’m expecting to see all images uploaded as a PropertyImages object to be displayed on the page access by the url pattern ‘properties’.

Instead no images are displayed, just the property title.

<img src="{{ property.images.url }}">

This ^^ in the template isn’t accessing the PropertyImages object

You may find it very instructive to walk through these steps using the Django shell (or shell_plus) to see what you get when you’re referring to property.images. (Hint: it’s not an instance of PropertyImages - it’s a collection. With the use of the ForeignKey field, you’re defining a many-to-one relationship between the PropertyImages and Property objects - you could have many Images for each property.)

As you’re reviewing the documentation, keep in mind that the Reporter and Article objects in the examples have the same type of relationship as your Property and PropertyImages have.

Ken thanks for your reply, using the Django shell, which I didn’t know about before, really helped and made it possible.

However my solution might not be the cleanest, if you have any improvements please let me know.

I created this function in the Property model

    def get_first_image(request):
        first_image = PropertyImages.objects.filter(my_property=request).values_list('images', flat=True)[0]
        return first_image

And then modified the template like so

{% for property in property_list.all %}
  {{ property.title }}
    <img src="{{ MEDIA_URL }}{{ property.get_first_image }}">
{% endfor %}

To serve locally during development I noticed my MEDIA_URL wasn’t working, I had to add this line to

        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                '' # *this line here*

I already had these defined in

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Thanks again

Hey - whatever works that you understand, works.

I will point out that you could use something like:

<img src="{{ property.images.all.0.url }}">

without adding that additional function.