I have these two models and as you can see they have a relationship.
JavaScript
x
7
1
class Post(models.Model):
2
text = models.TextField()
3
4
class PostImage(models.Model):
5
post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE)
6
image = models.FileField(upload_to = 'media/',blank=True, null=True)
7
As far as I understand if I query posts and push them to a template and post, I would expect to use something like this in my templates to retrieve the images URL attached to the posts but it doesn’t seem to work.
JavaScript
1
6
1
{% for post in posts %}
2
{% for post_image in post.post_image_set.all %}
3
{{post_image.image.url}}
4
{% endfor %}
5
{% endfor %}
6
What am I doing wrong?
Here is my views.py
file.
views.py
JavaScript
1
6
1
# Create your views here.
2
def index(request):
3
posts=Post.objects.filter(approved=True).order_by('-published_date')
4
context = {"posts":posts}
5
return render(request, 'post/home.html',context)
6
Advertisement
Answer
The default related name for a foreign key relational is the name of the model (PostImage) but in your template for loop you called it post_image Following relationships “backward”
change
JavaScript
1
2
1
{% for post_image in post.post_image_set.all %}
2
into
JavaScript
1
2
1
{% for post_image in post.postimage_set.all %}
2
Template code (with change)
JavaScript
1
6
1
{% for post in posts %}
2
{% for post_image in post.postimage_set.all %}
3
{{post_image.image.url}}
4
{% endfor %}
5
{% endfor %}
6