亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在帖子詳細信息頁面 Django 上顯示我的評論表單

如何在帖子詳細信息頁面 Django 上顯示我的評論表單

繁花如伊 2022-06-07 18:54:04
所以目前基本上,如果用戶想在我網站上的帖子中添加評論,它會將他們帶到另一個頁面,上面有表單。但是,我希望評論表單出現在實際的帖子詳細信息頁面上,這樣用戶就不必去另一個頁面發表評論了。到目前為止,我已經嘗試添加一些上下文內容并將評論表單位置的 url 更改為post_detail.html,并將comment_form.html' 的代碼放在那里,但這不起作用。以下是相關views.py 的add_comment_to_post觀點@login_required(login_url='/mainapp/user_login/')def add_comment_to_post(request,pk):    post = get_object_or_404(Post,pk=pk)    if request.method == 'POST':        form = CommentForm(request.POST)        if form.is_valid():            comment = form.save(commit=False)            comment.post = post            comment.author = request.user # add this line            comment.save()            return redirect('mainapp:post_detail',pk=post.pk)            # remove `def form_valid`    else:        form = CommentForm()    return render(request,'mainapp/comment_form.html',{'form':form})這是PostDetailView視圖。class PostDetailView(DetailView):    model = Post這是comment_form.html代碼<form class="post-form" method="post">    {% csrf_token %}    {{ form.as_p }}    <button type="submit" class="submitbtn">Comment</button></form>這是相關urls.py文件path('post/<int:pk>/comment/', views.add_comment_to_post, name='add_comment_to_post'),path('post/<int:pk>', views.PostDetailView.as_view(), name='post_detail'),因此,目前,在執行我認為可行的解決方案時,我將 comment_form.html 的代碼添加到 post_detail.html 文檔中,但它只顯示了Commenthtml 按鈕。我如何才能將 CommentForm 與帖子詳細信息頁面放在同一頁面上?
查看完整描述

2 回答

?
尚方寶劍之說

TA貢獻1788條經驗 獲得超4個贊

問題是,當 Django 渲染時PostDetailView,contextdict 沒有該form項目(該form項目僅在您的add_comment_to_post視圖中可用,因為 Django 模板引擎無法form從 dict 中找到該項目context,所以它沒有渲染任何東西。


您需要做的是更改您的PostDetailView并將其注入CommentForm到PostDetailView' 上下文中。這是一種方法:


class PostDetailView(DetailView):

        model = Post


        def get_context_data(self, **kwargs):

            context = super().get_context_data(**kwargs)

            context['form'] = CommentForm() # Inject CommentForm

            return context

您所做的實際上是覆蓋默認值,并將您的默認值作為 的一部分get_context_data注入,然后渲染它。CommentForm()context


查看完整回答
反對 回復 2022-06-07
?
慕的地8271018

TA貢獻1796條經驗 獲得超4個贊

你可以這樣嘗試:


class PostDetailView(DetailView):

        model = Post


        def get_context_data(self, **kwargs):

            context = super().get_context_data(**kwargs)

            context['comment_form'] = YourModelFormForComment()  # Your comment form

            return context

在模板中


{{comment_form.as_p}}


查看完整回答
反對 回復 2022-06-07
  • 2 回答
  • 0 關注
  • 147 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號