我正在尝试在博客中创建评论系统。这是视图部分。
def post_content(request,post_slug):
post= Post.objects.get(slug=post_slug)
new_comment=None
#get all comments that are currently active to show in the post
comments= post.comments.filter(active=True)
if request.method=='POST':
comment_form= CommentForm(request.POST)
if comment_form.is_valid():
# saving a ModelForm creates an object of the corresponding model.
new_comment= comment_form.save(commit=False)
new_comment.post=post
new_comment.save()
else:
comment_form=CommentForm()
return render(request,'blog/post_content.html',{'post':post,'comments':comments,'comment_form':comment_form})
还没有评论。现在,我不明白的是当我发表评论然后页面重新加载时,我立即看到评论(我不应该这样)。
根据我的理解,这应该是流程 - 当页面重新加载时(在提交评论之后),它首先进入视图并检索活动评论(这应该是空的,因为还没有保存,是吗?)它只在保存时才会保存if条件得到满足且表格有效,均在下面。保存后我没有检索到评论。但是,'comments'变量包含了我最近的评论。这是怎么回事?这是什么巫术?请有人为我说清楚!!
你缺少的是querysets are lazy。尽管在保存注释之前创建了查询集,但在迭代之前实际上不会进行查询,这在保存新注释后会在模板本身中发生。
请注意,正如Willem在评论中指出的那样,您确实应该在成功保存后重定向到另一个页面。这是为了防止用户刷新页面时重复提交。如果您愿意,可以重定向回同一页面,但重要的是您返回重定向而不是直接进入渲染。
new_comment.save()
return redirect('post-comment', post_slug=post_slug)