[Answered ]-Django View – 'Comment' object has no attribute 'comments'

1👍

obj is a Comment model, not an Article, hence it has no .comments attribute, but even if that was the case, it would be a RelatedManager for Comments, so it makes no sense to compare that with request.user.

If the Comment is related to the user, you need to work with a ForeignKey that injects the user into the Comment, so:

from django.conf import settings

class Comment(models.Model):
    article = models.ForeignKey(
        Article,
        on_delete=models.CASCADE,
        related_name='comments',
    )
    body = models.TextField()
    name = models.CharField(max_length=140)
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        related_name='comments',
        on_delete=models.CASCADE
    )
    date_added = models.DateTimeField(auto_now_add=True)

then you can filter with:

class CommentDelete(LoginRequiredMixin, DeleteView):
    model = Comment
    template_name = 'comment_delete.html'
    success_url = reverse_lazy('article_list')

    def get_queryset(self):
        return super().get_queryset().filter(
            user=self.request.user
        )

Note: The .get_absolute_url() method [Django-doc] should return a canonical URL, that means that for two different model objects the URL should be different and thus point to a view specific for that model object. You thus should not return the same URL for all model objects.

Leave a comment