为了账号安全,请及时绑定邮箱和手机立即绑定

如何在帖子详细信息页面 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 关注
  • 154 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号