理解django ModelForm提交

Understanding django ModelForm submission

我正在尝试在博客中创建评论系统。这是视图部分。

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})

还没有评论。现在,我不明白的是,当我 post 发表评论然后重新加载页面时,我会立即看到评论(我不应该这样)。

根据我的理解,这应该是流程-当页面重新加载时(提交评论后),它首先进入视图并检索活动评论(这应该是空的,因为 none已经保存了,是吗?) 只有满足if条件,form有效才保存,下面都是。保存后我还没有检索到评论。但是,“comments”变量仍然包含我最近发表的评论。 这是怎么回事?这是什么法术?请有人为我说清楚!

您缺少的是 querysets are lazy。尽管您在保存评论之前创建了查询集,但直到您迭代时才真正进行查询,迭代发生在保存新评论后模板本身。

请注意,正如 Willem 在评论中指出的那样,您确实应该在成功保存后重定向到另一个页面。这是为了防止用户刷新页面时重复提交。如果愿意,您可以重定向回同一页面,但重要的是您 return 重定向而不是跳转到渲染。

new_comment.save()
return redirect('post-comment', post_slug=post_slug)