我正在嘗試在博客中創(chuàng)建評論系統(tǒng)。這是視圖部分。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})還沒有評論?,F(xiàn)在,我不明白的是當(dāng)我發(fā)表評論然后頁面重新加載時,我立即看到了評論(我不應(yīng)該看到)。根據(jù)我的理解,這應(yīng)該是流程 - 當(dāng)頁面重新加載時(提交評論后),它首先查看并檢索活動評論(它應(yīng)該是空的,因為還沒有保存,是嗎?)它僅在if 條件滿足,form is valid ,都在下面。而且我保存后沒有檢索到評論。但是,' comments ' 變量仍然包含我最近發(fā)表的評論。這是怎么回事?這是什么法寶?請有人幫我說清楚!!
1 回答

波斯汪
TA貢獻(xiàn)1811條經(jīng)驗 獲得超4個贊
您缺少的是查詢集是 lazy。盡管您在保存評論之前創(chuàng)建了查詢集,但直到您進(jìn)行迭代后才會真正進(jìn)行查詢,這在保存新評論后發(fā)生在模板本身中。
請注意,正如 Willem 在評論中指出的那樣,您確實應(yīng)該在成功保存后重定向到另一個頁面。這是為了防止用戶刷新頁面時重復(fù)提交。如果愿意,您可以重定向回同一頁面,但重要的是您返回重定向而不是進(jìn)入渲染。
new_comment.save() return redirect('post-comment', post_slug=post_slug)
添加回答
舉報
0/150
提交
取消