Reputation: 8626
I am brand new to django and have run into a problem when trying to display a html page that contains multiple images.
What I am trying to achieve is for a parent record display all the related images, In my example below, ShowroomDetail is the parent and ShowroomPhoto is the child.
Using the Django admin screens, I have created one showroom and uploaded two images as children of this showroom. I can view both the showroom and images without an issue from the Django admin screens and can see that they are related.
Unfortunately when I try to display the same information using a template, I encounter the an error:
'ShowroomPhoto' object is not iterable
What am I doing wrong? In case of need I am using Django 1.6.2
Here are the contents of the various files.
models.py
from django.db import models
# Create your models here.
class ShowroomDetail(models.Model):
title = models.CharField(max_length=1000)
description = models.CharField(max_length=4000)
class ShowroomPhoto(models.Model):
showroom = models.ForeignKey(ShowroomDetail, related_name='photos')
photo = models.ImageField(upload_to='images/')
views.py
from django.shortcuts import render
from django.http import Http404, HttpResponse
from showroom.models import ShowroomDetail, ShowroomPhoto
# Create your views here.
def Displayshowroom(request):
showroom = ShowroomDetail.objects.all()[0]
photos = ShowroomPhoto.objects.all()[showroom.id]
return render(request, 'showroom.html', {'showroom': showroom, 'photos': photos})
showroom.html
<html>
<head>
<title>Showroom</title>
</head>
<body>
<ul>
<li>{{ showroom.title }}</li>
<li>{{ showroom.description }}</li>
<li>{{ showroom.id }}</li>
{% for photo in photos %}
<li><img src="{{ photo.url }}" height="420"/></li>
{% endfor %}
</u
</body>
</html>
Upvotes: 0
Views: 142
Reputation: 99620
When you do photos = ShowroomPhoto.objects.all()[showroom.id]
you are retrieving a single object, and not the queryset due to the []
(subscript).
You probably mean to filter
instead:
Change
photos = ShowroomPhoto.objects.all()[showroom.id]
to
photos = ShowroomPhoto.objects.filter(showroom__id=showroom.id)
Also, in the templates:
{% for photo in photos %}
<li><img src="{{ photo.url }}" height="420"/></li>
{% endfor %}
should be
{% for photo in photos %}
<li><img src="{{ photo.photo.url }}" height="420"/></li>
{% endfor %}
Now, your code would work fine.
Upvotes: 2