Shyrtle
Shyrtle

Reputation: 647

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

Upvotes: 1

Views: 1335

Answers (2)

JLeno46
JLeno46

Reputation: 1269

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.

Upvotes: 1

Razenstein
Razenstein

Reputation: 3717

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

Upvotes: 0

Related Questions