1

I am struggling to reference my ForeignKey from a basic DetailView in Django.

The models.py I am using:

class Posts(models.model):
    url = models.URLField()
    

class Comment(models.model):
    post = models.ForeignKey(Posts, related_name='comments', on_delete=models.CASCADE)
    content = models.CharField(max_length=500, blank=False)

views.py:

class PostDetailView(DetailView):
    model = Posts
    context_object_name = 'posts'

I am trying to reference the comments in my posts detail page.

posts_details.html:

{% for comment in posts.comments.all %}
  {{comment.content}}
{% endfor %}

I have also tried changing posts.comments.all to posts.comments_set.all and still am getting no results.

I feel like it is something small that I am missing, but I can't figure it out.

The data is there, and it was input correctly with the foreign key reference, but I cannot reference it through the detail view.


Edit with answer:

I was able to get this to work fairly simply by adding this to the comment model:

def get_absolute-url(self):
    return reverse('post_detail', kwargs={'pk': self.post.pk})

That allowed me to access the post in the post_detail.html with the following loop:

{% for comment in posts.comments.all %}
    {{comment.content}}
{% endfor %}
Shyrtle
  • 647
  • 5
  • 20

2 Answers2

1
class Posts(models.model):
    url = models.URLField()
    
    def get_all_comments(self):
        return Comment.objects.filter(post=self.pk)

Use this method, add the returned queryset to the context.

JLeno46
  • 1,186
  • 2
  • 14
  • 29
  • Ah, that does make sense. How would I point the template at what is returned from get_all_comments in the detailview html? – Shyrtle Dec 04 '20 at 23:39
  • It's well explained here: https://stackoverflow.com/questions/50596961/how-to-add-data-to-context-object-in-detailview, sorry it's kinda late here. – JLeno46 Dec 04 '20 at 23:42
  • No worries. Thanks for the help. I will check that post and try to get things working – Shyrtle Dec 04 '20 at 23:44
0

Your Posts model has no comments field ... so posts.comments.all is always empty. Unfortunately you do not get an error message if you try to access non existing fields in template tag

Razenstein
  • 3,532
  • 2
  • 5
  • 17