Reputation: 41
Very very beginner question that puzzles me. I have problems showing the foreign key ArtWorkImages in my template, so i wanted to debug it in the view, but the foreign key ArtworkImage is not available on Artwork:
my model:
from django.db import models
class Artwork(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.title
class ArtworkImage(models.Model):
property = models.ForeignKey(Artwork, related_name='images')
image = models.ImageField(upload_to = "images/")
the view:
from django.shortcuts import render
from erikheide.models import Artwork
from erikheide.models import ArtworkImage
def index(request):
artworks = Artwork.objects.all()[:5]
artwork = artworks[0]
images = artwork.artworkimage_set.all()
context = {'latest_poll_list': artworks}
return render(request, 'index.html', context)
the error:
> Traceback (most recent call last): File
> "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py",
> line 115, in get_response
> response = callback(request, *callback_args, **callback_kwargs) File "/home/fhp/Hentede filer/tastypie/django15/erikheide/views.py",
> line 13, in index
> images = artwork.artworkimage_set.all() AttributeError: 'Artwork' object has no attribute 'artworkimage_set'
The template that did not work (no images turn up)
{% if artworks %}
<ul>
{% for artwork in artworks %}
<li><a href="{{ artwork.title }}/">{{ artwork.body}}</a></li>
{% for image in artwork.images_set.all %}
<img src="{{ image.image.url }}">
{% endfor %}
{% endfor %}
</ul>
{% else %}
<p>No artworks are available.</p>
{% endif %}
Upvotes: 3
Views: 64
Reputation: 462
try
artwork.images.all()
instead
artwork.artworkimage_set.all()
image_set
is default name for RelatedManager. If related_name
specified with foreign key RelatedManager name redefines.
Upvotes: 0
Reputation: 474211
You have defined a related_name
on the ForeignKey
field, you need to use it to follow the relationship.
Replace:
images = artwork.artworkimage_set.all()
with:
images = artwork.images.all()
Also see: What is `related_name` used for in Django?
Upvotes: 2