Search code examples
pythondjangoforeign-keysdetailview

Reference ForeignKey in Django DetailView


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 %}

Solution

  • 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.