我覺得我真的很接近,但還沒有完成。請耐心等待,因爲在學習django的初級階段我非常喜歡。django表單 - 如何在用戶發佈新評論時更新以前評論中的用戶數據
我有一個功能,用戶可以在每篇博文中發表評論。我想顯示每個用戶在他名字旁邊的評論總數。如果該用戶在4個不同的帖子上留下了4條評論,我希望它在我的網站上的每條評論中都顯示他的姓名旁邊顯示「4條總評論」。
我做了一個模型方法,我把我的看法,它會自動更新每個用戶的總評論。唯一的問題是,如果用戶留下了兩條評論,只有他的最新評論會顯示「2條評論」。他的前一個只顯示「1」。
我的問題是,如何在用戶留下新評論時更新上一個條目?
models.py
class Comment(models.Model):
...
post = models.ForeignKey(Post, related_name="comments")
user = models.ForeignKey(User, related_name="usernamee")
email = models.EmailField(null=True, blank=True)
picture = models.TextField(max_length=1000)
...
review_count = models.IntegerField(default=0)
class UserProfile(models.Model):
...
def user_rating_count(self): #This is what adds "1" to the user's total post count
user_ratings =
Comment.objects.all().filter(user_id=self.user.id).count()
user_ratings += 1
return user_ratings
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
comment.user = request.user
comment.email = request.user.email
comment.picture = request.user.profile.profile_image_url()
comment.review_count = request.user.profile.user_rating_count() #This is where I'd like it to update, but it doesn't seem to work this way
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)
模板
{% for comment in post.comments.all %}
<p>{{ comment.user.first_name }} <b>{{ comment.user.last_name }}</b> {{ comment.review_count }}</p>
{% endfor %}
的評論一度=名姓1 的評論兩次,他的第二個評論=名字姓氏2,但第一個評論保持不變。
關於如何正確地做到這一點的任何想法?任何幫助是極大的讚賞!
感謝輸入和鏈接,我已經看了放進去,發現一個解決方案!您的代碼在頂部有點偏離,而不是「return self.usernamee.count()」,這給了我一個錯誤,我使用了「return self.user.comment_set.count」,它的工作原理! – dmandres
是的,如果評論直接與'UserProfile'模型相關,但你也可以使用'self.user.usernamee.count()'(這就是'comment_set'是'comment_set'是默認的如果你沒有指定任何相關的名字) – danidee
隨時標記我的答案是正確的。因爲它解決了你的問題:-) – danidee