A_K
A_K

Reputation: 922

How to add a Context to a ListView Class Based View

I am having trouble fixing a minor issue related to my comments section, I have created a comment section for my Item detail view which is working fine and showing the no. of comments an Item have. I have another List view which I want to reflect the no. of comments each item has.

Here is the models.py

class Comment(models.Model):
    STATUS = (
        ('New', 'New'),
        ('True', 'True'),
        ('False', 'False'),
    )
    item = models.ForeignKey(Item, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="ItemComments")
    comment = models.CharField(max_length=250, blank=True)
    status = models.CharField(max_length=10, choices=STATUS, default='New')
    create_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return '{} by {}'.format(self.subject, str(self.user.username))

    def total_comments(self):
        return self.comment.count()

Here is the item detail view.py

class ItemDetailView(DetailView):
    model = Item
    template_name = "product.html"

    def get_context_data(self, **kwargs):
        comments = Comment.objects.filter(item=self.object, status='New').order_by('-create_at')
        context = super().get_context_data(**kwargs)
        context["comments"] = comments
        context["total_comments"] = comments.count()
        return context

Here is the list view which I am working on the add the count as well. I have written the code but it is not reflecting the correct count is reflecting the total count of comments for all items, I want to show the no. of comments for each item separately.

class DesignerOnlyPostListView(ListView):
    model = Item
    template_name = "designer_only_posts.html"
    context_object_name = 'items'
    paginate_by = 6

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Item.objects.filter(designer=user).order_by('-timestamp')

    def get_context_data(self, **kwargs):
        comments = Comment.objects.all()
        context = super().get_context_data(**kwargs)
        context["total_comments"] = comments.count()
        return context

here is the template

                    {% for item in items %}
                            {% if item.image %}
                                <a href="{{item.get_absolute_url}}">
                            {% endif %}
                                <h4><strong>{{item.title}}</strong></h4>
                                    <tr>
                                        <td>No. of Reviews:</td>
                                        <td>{{ total_comments }}</td>
                                    </tr>                                                                                                        
                    {% endfor %}

Upvotes: 1

Views: 714

Answers (1)

Kareem
Kareem

Reputation: 609

In you're models I'd add a related_name to the item attribute.

item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name="comments")

That way in your comments you can call this directly

{% for item in items %}
        {% if item.image %}
              <a href="{{item.get_absolute_url}}">
        {% endif %}
        
         <h4><strong>{{item.title}}</strong></h4>
         <tr>
           <td>No. of Reviews:</td>
            <td>{{ item.comments.all.count }}</td>
         </tr>                                                                                                        
{% endfor %}

Upvotes: 1

Related Questions