![](/img/trans.png)
[英]how can i get the “post id”(foreign key field connected with comment model) to the django comments form without post_detail page in django
[英]Django - displaying each individual user's comment count on a post_detail template
我設置了我的評論,用戶可以在其中評論博客文章,並將這些評論顯示在post_detail.html
模板中。 我想在每個用戶的評論旁邊(在任何帖子中)顯示每個用戶的評論總數。
例如,我想對每個用戶說user 1: 4 comments
,依此類推。 如果user 1
在4個不同的帖子上留下了4條評論,則所有4個帖子應顯示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 %}
...
我一直在嘗試通過模型的user_rating_count
方法來完成此user_rating_count
,但是我只能手動選擇user=1
或user=2
,這是user_rating_count
,但它不是動態的。 我正在嘗試檢索留下評論的用戶。
嘗試:
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)
現在在html中
{% for user in users %}
<b>{{user.username}}</b>:{{user.ratings}}
{% endfor %}
這將顯示每個用戶的用戶username : total_comments
。
您需要從urls
調用user_rating_count
函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.