I can’t display a comment list for a post in the Django template

Asked

Viewed 78 times

0

I have a method called get_comments in the models that returns the comments of my post, but when I display in the template, only the posts are displayed, the Comments are not. Django does not return any Exception to me

Model

from django.db import models
from authentication.models import User

TYPE_POST = (
   ('0', 'Post'),
   ('1', 'Comment')
)

class Post(models.Model):
    content = models.TextField(blank=True, null=True)
    image = models.ImageField(upload_to='imagens/', blank=True, null=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    reactions = models.IntegerField(default=0)
    type_post = models.CharField(max_length=1, choices=TYPE_POST, default='0')
    pub_date = models.DateTimeField(auto_now_add=True)
    commented_post = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True)

   @property
   def get_comments(self):
       comments = Post.objects.filter(type_post='1', commented_post=self.commented_post)

       return comments

   class Meta:
       ordering = ['-pub_date']

Template

{% for post in posts %}
    <p>post.content</p>
    {% for comment in post.get_comments %}
      <p>{{ comment.content }}</p>
      <p>{{ comment.pub_date }}</p>
    {% endfor %}
{% endfor %}
  • Juliana can you confirm that you have created posts of type 1? In your modeling, would be comments

  • Yes, in the Django shell, I query and it returns posts of type 1

1 answer

1


I think to solve this, you’d need to change your method of retrieving comments a little bit:

   @property
   def get_comments(self):
       comments = Post.objects.filter(type_post='1', commented_post=self)

The secret would be in the part commented_post=self instead of commented_post=self.commented_post. The second is filtering comments that were made by himself as a post. The self in this case will be the post where the comment was made.

  • Thank you, I managed to solve!

  • Nice! Taking advantage, I don’t know if you already know, but we have a group of Django in Telegram very nice. If you already use and are interested: https://t. me/djangobrasil

Browser other questions tagged

You are not signed in. Login or sign up in order to post.