如何在帖子详细信息页面 Django 上显示我的评论表单

所以目前基本上,如果用户想在我网站上的帖子中添加评论,它会将他们带到另一个页面,上面有表单。但是,我希望评论表单出现在实际的帖子详细信息页面上,这样用户就不必去另一个页面发表评论了。


到目前为止,我已经尝试添加一些上下文内容并将评论表单位置的 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 与帖子详细信息页面放在同一页面上?


繁花如伊
浏览 166回答 2
2回答

尚方宝剑之说

问题是,当 Django 渲染时PostDetailView,contextdict 没有该form项目(该form项目仅在您的add_comment_to_post视图中可用,因为 Django 模板引擎无法form从 dict 中找到该项目context,所以它没有渲染任何东西。您需要做的是更改您的PostDetailView并将其注入CommentForm到PostDetailView' 上下文中。这是一种方法:class PostDetailView(DetailView):&nbsp; &nbsp; &nbsp; &nbsp; model = Post&nbsp; &nbsp; &nbsp; &nbsp; def get_context_data(self, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; context = super().get_context_data(**kwargs)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; context['form'] = CommentForm() # Inject CommentForm&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return context您所做的实际上是覆盖默认值,并将您的默认值作为 的一部分get_context_data注入,然后渲染它。CommentForm()context

慕的地8271018

你可以这样尝试:class PostDetailView(DetailView):&nbsp; &nbsp; &nbsp; &nbsp; model = Post&nbsp; &nbsp; &nbsp; &nbsp; def get_context_data(self, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; context = super().get_context_data(**kwargs)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; context['comment_form'] = YourModelFormForComment()&nbsp; # Your comment form&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return context在模板中{{comment_form.as_p}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python