Access foreign key image in template
<p>I have the following models:</p>

<pre><code>class Car(models.Model):
    # some fields

class CarPhotos(models.Model):
    image = models.ImageField(upload_to='somewhere')
    car = models.ForeignKey(Car)
</code></pre>

<p>in views.py:</p>

<pre><code>def car_list(request):
    cars = Car.objects.all()
    return render(request, 'borsa/car_list.html', {'cars': cars})
</code></pre>

<p>in car_list.html:</p>

<pre><code> {% for car in cars %}
    &lt;a href="car/{{ car.pk }}/view/"&gt;
      &lt;img class="media-object tmbpic" src="{{ car.carphotos_set.all.0.image.url }}" alt="kola"&gt;
    &lt;/a&gt;
</code></pre>

<p>The first method I've used was to use inline formsets but I had no clue how to access the images. Can you please point me in the right direction of how to access images according to Car objects ? I mean every Car must have a couple of images and I need to display only the first one in list view, but then I need to display all of them in Detail view. </p>

<p>To display all of them, you need to do something like:</p>

<pre><code>{% for car in cars %}
    {% for photo in car.carphotos_set.all %}
       &lt;img src="{{ photo.image.url }}"&gt;
    {% endfor %}
{% endfor %}
</code></pre>

<p>So loop through the cars, then nest-loop through the images per car.</p>

python django