简体   繁体   中英

Django - displaying each individual user's comment count on a post_detail template

I have my comments set up where users can review blog posts and have those reviews show up in the post_detail.html template. I would like to display the total number of comments for every user, right next to their comments (in any post).

For example, I'd like it to say user 1: 4 comments , and so on, for each user. If user 1 has left 4 comments on 4 different posts, all 4 posts should display user 1: 4 comments .

models.py

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='profile')

...

def user_rating_count(self):
    user_ratings = Comment.objects.filter(user=2).count()
    return user_ratings

...

class Comment(models.Model):
    post = models.ForeignKey(Post, related_name="comments")
    user = models.ForeignKey(User, related_name="usernamee")
    ...
    review_count = models.IntegerField(default=0)

views.py

@login_required
def add_comment(request, slug):
    post = get_object_or_404(Post, slug=slug)

    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post # Makes the post linked to the comment
            comment.user = request.user # Makes the user linked to the comment
            comment.email = request.user.email
            comment.picture = request.user.profile.profile_image_url()
            comment.review_count = request.user.profile.user_rating_count()
            comment.save()

            return redirect('blog:post_detail', slug=post.slug)
    else:
        form = CommentForm()

    template = "blog/post/add_comment.html"
    context = {'form': form}
    return render(request, template, context)

post_detail.html

...
{% for comment in post.comments.all %}
    {{ comment.review_count }}
{% endfor %}
...

I've been trying to accomplish this through my model's user_rating_count method, but I can only manually select user=1 or user=2 , which works, but it isn't dynamic. I'm trying to retrieve the user that left the comment.

Try:

from django.db.models import Count

def user_rating_count(request):
    users = User.objects.all().annotate(ratings=Count('comment'))
    context={'users':users}
    render(request, 'file.html', context)

Now in html

{% for user in users %}
    <b>{{user.username}}</b>:{{user.ratings}}
{% endfor %}

This will show, username : total_comments for every user.

You need to make a call to user_rating_count function from your urls .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM