0

Soy nuevo en django y quiero listar objetos de mi modelo Post junto con sus respectivos comentarios con vistas basadas en clases ListView, pero por cada post se muestran todos los comentarios de todos los post ya que no sé como hacer para que se filtren los comentarios por post con esta clase. ¿Alguien podría ayudarme? no sé si deba cambiar la relacion entre el modelo Post y Comment, o modificar la vista, o simplemente cambiar la forma de presentar los objetos en mi plantilla...

Models.py

class Post(models.Model):
    """Post model."""

    user = models.ForeignKey(User, on_delete=models.CASCADE)
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
    title = models.CharField(max_length=255)
    photo = models.ImageField(upload_to="posts/photos")
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    def __str__(self):
        """Return title and username"""
        return "{} by @{}".format(self.title, self.user.username)


class Comment(models.Model):
    """Comment model."""
    
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True)
    comment = models.TextField(blank=True)

    def __str__(self):
        """Return user and pk"""
        return "{} by @{}".format(self.pk, self.user.username)

Views.py

class PostsFeedView(LoginRequiredMixin, ListView):
    """Return all published posts."""

    template_name = "posts/feed.html"
    model = Post
    ordering = ("-created")
    paginate_by = 30
    context_object_name = "posts"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['comments'] = Comment.objects.all()
        context['form_comments'] = CommentForm()
        return context```

# parte de la plantilla

```{% for comment in comments %}
        <div class="media mb-2">

            {% if comment.user.profile.picture %}
                <img class="d-flex mr-2 rounded-circle" width="50px" height="50px" src="/media/{{ comment.user.profile.picture }}" alt="">
            {% else %}
                <img class="d-flex mr-2 rounded-circle" src="http://placehold.it/50x50" alt="">
            {% endif %}

            <div class="media-body">
                <h5 class="mt-0">{{comment.user.username}}</h5>
                {{comment.comment}}
            </div>
        </div>
    {% endfor %}
</div>

1 respuesta 1

1

En tu view no es necesario que regreses los comentarios, ya que regresa todos.

En tu template iria asi:

{% for post in objects_list %}

 Titulo post: {{ post.campo }}

    {% if post.comment_set.all %}
        {% for comment in post.comment_set.all %}
            <div class="media mb-2">

                {% if comment.user.profile.picture %}
                    <img class="d-flex mr-2 rounded-circle" width="50px" height="50px" src="/media/{{ comment.user.profile.picture }}" alt="">
                {% else %}
                    <img class="d-flex mr-2 rounded-circle" src="http://placehold.it/50x50" alt="">
                {% endif %}

                <div class="media-body">
                    <h5 class="mt-0">{{comment.user.username}}</h5>
                    {{comment.comment}}
                </div>
            </div>
        {% endfor %}
    {% endif %}

{% endfor %}

Como tu modelo Comment tiene relación a un post, cuando tienes un post puedes obtener todos sus comentarios relacionados con {{ post.comment_set.all }} para template y post.comment_set.all() para python lo cual te devuelve un queryset con los comentarios o vacio si no tiene.

Si quieres ahorrarte escribir el all puedes agregar un método al modelo Post así:

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
    title = models.CharField(max_length=255)
    photo = models.ImageField(upload_to="posts/photos")
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    def comentarios(self):
        return self.comment_set.all()

    def __str__(self):
        """Return title and username"""
        return "{} by @{}".format(self.title, self.user.username)

Así en lugar de llamar post.comment_set.all, lo llamarías como {% for comment in post.comentarios %} en template y post.comentarios() en python.

1
  • Había dejado este proyecto de práctica y empecé otro, el cual ya terminé. Hoy retomé este y me sirvió tu aporte. Te agradezco un montón!!! el 2 jun. 2021 a las 21:30

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.